问题描述
我可以显示商店内的商品及其评论.如何获得评论最多的热门商品?我的评论在另一个数据库表中而不是商店和项目.
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.
控制器
@shop = Shop.find(params[:id])
@item = Item.where(:shop_name => @shop.name)
查看
<% @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?
谢谢
所以我有一个shop
、item
、review
表.
在我的物品模型
has_many :reviews, as: :reviewable
has_many :shops
在我的评论模型和商店模型中是
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.
推荐答案
如果我理解正确你的 ER 模型,你可以试试这个:
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")
可能有一些错别字,但你懂的.也可能您想要创建某种加权分数,否则在这种情况下,具有 5 星评价的项目将高于具有 50 条 4 星评价的项目.
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.
此外,我在 select
块中定义的所有自定义列都是字符串类型,因此如果您要对它们进行任何算术运算,则需要手动对它们进行类型转换.
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.
这篇关于Ruby on Rails:根据评论最多的平均评分对用户进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!