ga-wdi-exercises / project2

[project]
1 stars 30 forks source link

Rating system #835

Closed laurkgol closed 7 years ago

laurkgol commented 7 years ago

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?

amaseda commented 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
amaseda commented 7 years ago

Did this work out?

@laurkgol

amaseda commented 7 years ago

Going to close this one but feel free to re-open if this issue persists.

laurkgol commented 7 years ago

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?

AndyWhitley commented 7 years ago

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.

superbuggy commented 7 years ago

Just wanted to add that there is also a method .sum in ruby.

AndyWhitley commented 7 years ago

Hey @laurkgol , were you able to get the rating system working with the above solutions?

amaseda commented 7 years ago

Going to close this one but feel free to re-open if you've got any questions/comments about this issue.