Reputation: 8587
I'm able to display the items and their reviews that are within the shop. How do I get the top items with most reviews? My reviews are in another database table than shop and item.
Controller
@shop = Shop.find(params[:id])
@item = Item.where(:shop_name => @shop.name)
View
<% @item.each do |u| %>
<%= u.reviews.average('rating') %>
<%= u.reviews.count %>
<% end %>
Is there an easy method where I can order based on the highest rating with most reviews or something? Or maybe its better to separate highest rating and most reviews and let users click on a link to filter?
Thanks
EDIT:
So I have a shop
, item
, review
table.
In my items model
has_many :reviews, as: :reviewable
has_many :shops
In my reviews model and shops model is
belongs_to :user
In my reviews table, its set so when a user reviews an item, it adds a record to the database, and I use the average
of all the records thats associated with that item and display it that within the shop.
Upvotes: 2
Views: 3159
Reputation: 2853
If I understood correctly Your ER model, You can try this:
@items = Item.where(:shop_name => @shop.name).joins(:reviews)
.select("items.id, avg(reviews.rating) as average_rating, count(reviews.id) as number_of_reviews")
.group("items.id")
.order("average_rating DESC, number_of_reviews DESC")
There could some typos, but You get the idea. Also probably You will want to create some kind of weighted score, otherwise in this case item with one 5 star review will be higher than item with fifty 4 star reviews.
Also all the custom columns I defined in select
block will be of string type, so You will need to typecast those manually if You will do any arithmetic operations on them.
Upvotes: 5