我的应用程序中有一个相当简单的标记模型。
Photo has_many :taggings
Photo has_many :tags, :through => :taggings
Tag has_many :taggings
Tag has_many :photos, :through => :taggings
Tagging belongs_to :photo
Tagging belongs_to :tag
我现在要做的是检索所有标签,按照标记该标签的照片数量排序,并在标签旁边显示该数字。
你怎么写这样的查询?而且,当您为每个代码显示tag.photos.count
时,如何阻止n + 1查询?
谢谢!
答案 0 :(得分:2)
SQL是您的朋友 - 假设Tag
模型具有name
属性:
tags = Tag.joins(:photos).
group("tags.id").
select("tags.id, tags.name, count(*) as num_photos").
order("num_photos")
tags.all.each do |tag|
puts [tag.id, tag.name, tag.num_photos].join(",")
end
您可以将其投放到范围内(例如with_counts
)并执行以下操作:
Tag.where(["tags.name = ?",sassy]).with_counts.first.num_photos
答案 1 :(得分:0)
这是一个黑客,但假设所有标记都是标记和照片之间的有效链接,您可以使用
Tagging.group("tag_id").order("count(*) desc").count
获取所有标记ID的有序哈希以及与该标记关联的标记/照片数量。