Ruby on Rails: Order users based on average ratings with most reviews?

拈花ヽ惹草 提交于 2019-11-28 09:59:19

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/19339140/ruby-on-rails-order-users-based-on-average-ratings-with-most-reviews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!