Rails 3.1
I’ll simplify my application to get at my question.
I have two tables: Items and Reviews
Items has a column “Average_Rating” and Reviews has a column “Item_ID” and “Rating”
For each item, I’d like to store the average rating for its corresponding reviews. Although I can’t figure it out, I feel like what I want to do is add something to the create and update methods in the Reviews Controller along the lines of:
@review = Review.find(params[:id])
@item = Item.find(@review.Item_ID)
reviews_to_sum = Reviews.find_by_item_id(@item.id)
@item.Average_Rating = reviews_to_sum.Rating.sum/reviews_to_sum.count
I recognize, however, that the above probably isn’t close to correct… I’m a beginner and I’m stuck.
And I do want to store the Average_Rating in the database, as opposed to calculating it when I need it, for a variety of reasons.
1 Answer