给定:
class Categories < ActiveRecord::Base
has_many :posts
end
和
class Posts < ActiveRecord:Base
attr_accessible :category_id
belongs_to :category
end
如何获取至少有一个关联帖子的所有类别的数组?
更好的(就性能而言)解决方案是在categories
表中有一个计数列,并在belongs_to关联声明(您已经研究过)上:counter_cache => true
。
更多信息在这里: http://guides.rubyonrails.org/association_basics.html#belongs_to-counter_cache
如果您的表相对较小,则可以查询: Category.joins(:posts).group(:category_id).having('count(category_id) >= ?', 1)