Question

UPDATE

I have a simple rails app with a home page displaying the highest rated albums, using this code in my controller (used code from this solution: How to display highest rated albums through a has_many reviews relationship):

def home
    @top_ratings = Album.joins(:reviews).select("*, avg(reviews.rating) as average_rating").group("albums.id").order("average_rating DESC")

    @top_seven = @top_ratings[0...7]
end

In my home.html.erb file I am displaying each album and have a link_to tag that takes the user to the album's show page:

<tbody>
  <tr>
    <% @top_seven.each do |album| %>
      <td><%= link_to (image_tag album.picture, size: '150x150'), album_url(album)  %>    </td>
    <% end %>
  </tr>
</tbody>

The data appears fine, however when I click on the link, I get a "undefined method `name' for nil:NilClass" error on the album's show page.

On my rails server I noticed that the album id's associated with the @top_ratings and @top_seven variables are different than the album's actual id, which is why I am getting the error.

Does anyone know how to refactor @top_ratings so that it will return the highest rated albums with their correct id number so that the link will work properly?

Was it helpful?

Solution 2

By changing the code above from this:

<td><%= link_to (image_tag album.picture, size: '150x150'), album_url(album) %></td>

To this:

<td><%= link_to (image_tag album.picture, size: '150x150'), album_url(album.album_id) %></td>

It will pull the correct id for the album and allow the link_to to work properly.

OTHER TIPS

When Album.find_by_id(params[:id]) has no match, @album becomes nil. NilClass does not have a method named name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top