mardi 1 décembre 2015

Show View Returning Error: undefined method `each'

I researched this topic here on Stack Overflow but I still can't seem to figure out what I'm doing wrong.

My show.html view file is throwing this error:

undefined method `each' for #<Advertisement:0x007fce42676a70>

when I'm clicking on my individual ads within my browser locally.

My show.html view code:

<h1><%= @advertisement.title %></h1>

<%= link_to "Edit advertisement", edit_advertisement_path, class: 'btn btn-success' %>
<%= link_to "Delete advertisement", @advertisement, method: :delete, class: 'btn btn-danger', data: { confirm: 'Are you sure you want to delete this advertisement?' } %>

<div class="row">
  <div class="col-md-8">
    <p class="lead"><%= @advertisement.copy %></p>
    <% @advertisement.each do |advertisement| %>
    <div class="media">
      <div class="media-body">
        <h4 class="media-heading">
          <%= link_to advertisement.title, advertisement_path(@advertisement) %>
        </h4>
      </div>
    </div>
  <% end %>
  </div>
  <div class="col-md-4">
    <%= link_to "New Advertisement", new_advertisement_path(@advertisement), class: 'btn btn-success' %>
  </div>
</div>

My advertisement controller code:

class AdvertisementsController < ApplicationController
  def index
    @advertisements = Advertisement.all
    # render('advertisements/index.html.erb')
  end

  def show
    # raise 'this is the show action'
    @advertisement = Advertisement.find(params[:id])
    # render 'advertisements/index.html.erb'
  end

  def edit
    @advertisement = Advertisement.find(params[:id])
  end

  def new
    @advertisement = Advertisement.new
  end

  def create
    @advertisement = Advertisement.new
    @advertisement.title = params[:advertisement][:title]
    @advertisement.copy = params[:advertisement][:copy]
    @advertisement.price = params[:advertisement][:price]

    if @advertisement.save
      flash[:notice] = "Advertisement was saved."
      redirect_to @advertisement
    else
      flash[:error] = "There was an error saving the advertisement. Please try again."
      render :new
    end
  end

  def update
    @advertisment = Advertisement.find(params[:id])
    @advertisment.title = params[:advertisement][:title]
    @advertisment.copy = params[:advertisement][:copy]
    @advertisment.price = params[:advertisement][:price]

    if @advertisement.save
      flash[:notice] = "Advertisement was updated."
      redirect_to @advertisement
    else
      flash[:error] = "Error saving advertisement. Please try again."
      render :new
    end
  end
end

From researching it, I believe my issue is that the advertisement object has to be an array. What do I need to change to get the show view to work properly? Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire