Rails 标记:按出现次数查找标签
我的应用程序中有一个相当简单的标记模型。
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 查询?
谢谢!
I have a fairly simple tagging model in my app.
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
What I'd like to do now is retrieve all the tags, order them by the number of photos tagged with that particular tag, and show that number along side the tag.
How do you write a query like that? And, how do you prevent an n+1 query when you show tag.photos.count
for each tag?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SQL 是你的朋友 - 假设
Tag
模型有一个name
属性:你可以将其放入范围内(例如
with_counts< /code>) 并执行以下操作:
SQL is your friend - assuming the
Tag
model has aname
attribute:You could throw that in a scope (e.g.,
with_counts
) and do things like:这是一个 hack,但假设所有标签都是标签和照片之间的有效链接,您可以使用它
来获取所有标签 id 的有序哈希以及与该标签关联的标签/照片的数量。
This is a hack, but assuming that all the Taggings are valid links between a tag and a photo you could use
to get an ordered hash of all the Tag ids and the number of taggings/photos associated with that tag.