Closed laurkgol closed 7 years ago
In this example, @sum_rating
would apply to just the ratings for @book
.
@average_rating
, however, needs to be modified. Instead of dividing by the number of all books, it should be divided by the number of ratings made for that particular book...
@average_rating = @sum_rating / @book.reviews.length
Did this work out?
@laurkgol
Going to close this one but feel free to re-open if this issue persists.
I'm still working on this, part of the class Review is the rating key so how do I get all of the ratings for the book?
In the show
action on the MeetingsController
, you would want to query for the book related to that meeting, then query for all associated Reviews of that book, then (using an enumarable) iterate through all of the reviews and average all of the rating
attributes on those Reviews:
In meetings#show
@meeting = Meeting.find(params[:id])
# Check rails routes to ensure this is how you access a specific meeting
@book = @meeting.book
@reviews = @book.reviews
@sum_ratings = @reviews.reduce(0) { |sum, review| sum + review.rating }
@average_rating = @sum_rating / @reviews.length
You could then use these variables in your meetings/show.html.erb
file to template out the meeting and book's info.
Just wanted to add that there is also a method .sum
in ruby.
Hey @laurkgol , were you able to get the rating system working with the above solutions?
Going to close this one but feel free to re-open if you've got any questions/comments about this issue.
I'd like to average the rating for each book in my book club.
Andy gave me this code to use in the book #show:
@book = Book.find(params[:book_id]) @sum_rating = @book.reviews.reduce do |sum, rating| sum + rating end
@average_rating = @sum_rating / Books.all.length
but i'm not sure how to implement it, wouldn't the average rating in this case be for all of the books instead of for each individual book?