[英]How do I create a list of the most used tags associated with a model?
I wasn't too sure how to title this question, but I'll explain here. 我不太确定如何为这个问题加上标题,但是我将在这里解释。 I'm on rails 4 and I'm trying to build a wine review app. 我在第4条轨道上,正在尝试构建葡萄酒评论应用。 I have a wine model and a review model that is associated.. 我有一个酒模型和一个关联的评论模型。
wine.rb wine.rb
has_many :reviews
review.rb review.rb
belongs_to :wine
has_many :taggings
has_many :tags, through: :taggings
My reviews have tags that are made through a has_many
has_many
relationship with a separate model "tagging.rb" 我的评论包含通过has_many
has_many
关系与单独的模型“ tagging.rb”建立的标签
tag.rb tag.rb
has_many :taggings
has_many :reviews, through: :taggings
tagging.rb tagging.rb
belongs_to :review
belongs_to :tag
On my wine show.html.erb
page I display a list of all the reviews and each review shows what it has been tagged with. 在我的wine show.html.erb
页面上,我显示了所有评论的列表,每个评论都显示了它的标签。 I am trying to count the number of times that each tag has been used on the reviews and display a list of the top 5 tags the wine has received, based on all the reviews. 我正在尝试计算每个标签在评论中的使用次数,并根据所有评论显示葡萄酒收到的前5个标签的列表。 How would I do this? 我该怎么做?
I am able to get a list of the top 5 used tags app wide with this in my review.rb 我可以在我的review.rb中获得最广泛使用的5个应用标签列表。
def self.tag_counts
Tag.select("tags.*, count(taggings.tag_id) as count").
joins(:taggings).group("taggings.tag_id").order("count DESC").limit(5)
end
But I want to be able to get the top 5 used on a specific wine. 但我希望能够获得特定葡萄酒使用的前5名。 Thanks. 谢谢。
Update 更新
Thanks to @kardeiz for helping me though this :). 感谢@kardeiz通过此帮助我:)。 I ended up using this to get the result I was looking for 我最终使用它来获得想要的结果
Tag.joins(:reviews => :wine).where("wines.id = ?", self.id).group("taggings.tag_id").select("wines.id, tags.*, COUNT(taggings.tag_id) as count").order('count DESC').limit(5)
then in my view I have @wine.tag_counts.each
to iterate over each tag. 然后在我看来,我有@wine.tag_counts.each
遍历每个标签。 Then each iteration I have it print out the tag name and the count. 然后,我每次迭代都会打印出标签名称和计数。
I don't have test data readily available to confirm this works, but I think this is what you want (split for legibility): 我没有可用的测试数据来确认这项工作,但是我认为这是您想要的(为清晰起见而拆分):
Tag
.joins(:reviews => :wine)
.where('wines.id = ?', whatever_id)
.group("taggings.tag_id")
.order("COUNT(taggings.tag_id) DESC")
.limit(5)
EDIT 编辑
Sorry, I misread the question. 抱歉,我看错了问题。 I think this should do what you want (though I haven't tested): 我认为这应该做您想要的(尽管我还没有测试):
in_sql = Tag
.joins(:reviews => :wine)
.group("taggings.tag_id")
.select("wines.id as wid, tags.*, COUNT(taggings.tag_id) as count")
.to_sql
out_sql = %Q{
select *
from (#{in_sql})
where wid = #{whatever_id}
order by count
limit 5
}
ActiveRecord::Base.connection.execute(out_sql)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.