查找带有文章的标签
问题描述:
在博客应用程序中我想显示带有文章的标签列表。查找带有文章的标签
class Article < AR::B
has_and_belongs_to_many :tags
end
class Tag < AR::B
has_and_belongs_to_many :articles
end
标记范围是什么样的?
Tag.joins(:articles) ... # should return tags associated to at least 1 article
答
用Ruby/Rails做到这一点的一种方法就是这个。
Tag.includes(:articles).select { |tag| tag.articles.any? }
.includes
可以确保物品装载标签旁边,这是比加载它们当每个标签的物品被重复时更有效。
然后解析该数组以仅选择与文章关联的数组。
谢谢@ thomas-klemm正是我所需要的。 – olimart 2013-03-25 21:21:55
不客气:--D – 2013-03-25 21:27:20