Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to display highest rated albums through a has_many reviews relationship
    primarykey
    data
    text
    <p>I'm setting up a simple ruby/rails app where users can review albums. On an album's show page I average all the user reviews associated with that album through this code in my albums controller </p> <pre><code>def show @album = Album.find_by_id(params[:id]) if @album.reviews.present? @ratings = Review.where(album_id: @album).average(:rating).truncate(2) else render 'show' end end </code></pre> <p>This gives me an average rating for each album. On my home page (routed through a different controller) I want to display the top 7 albums with the highest average rating. </p> <p>What I originally did was put this code into the separate home page controller: </p> <pre><code>@albums = Album.all @ratings = @albums.each {|album| album.reviews.average(:rating).to_f} @ranked_ratings = @ratings.sort_by {|rating| rating} @top_seven = @ranked_ratings.reverse[0...7] </code></pre> <p>I thought I found the solution until I realized all I'm showing is the last 7 albums entered into the database.</p> <p>Going back to the drawing board I have been able to get an array of all the albums (each element within the array is a list of reviews associated with that album) with this code in my controller:</p> <pre><code>@albums = Album.all @ratings = @albums.collect {|album| album.reviews} </code></pre> <p>I'm stuck at this point trying to figure out how to cycle through @ratings and find the average rating for each album_id, then order those records by the highest average rating and display them in a view. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload