ActiveRecord的查找包含至少一个项的类别 [英] ActiveRecord find categories which contain at least one item

查看:142
本文介绍了ActiveRecord的查找包含至少一个项的类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

支持我有两个模型的项目和种类,在许多对许多关系

Support I have two models for items and categories, in a many-to-many relation

class Item < ActiveRecord::Base
  has_and_belongs_to_many :categories 

class Category < ActiveRecord::Base
  has_and_belongs_to_many :items

现在我想筛选出其中至少包含一个项目,会是怎样做到这一点的最好办法类别?

Now I want to filter out categories which contain at least one items, what will be the best way to do this?

推荐答案

请注意,其他人answererd什么都不是高性能!

最高效的解决方案:

更好用的 counter_cache 工作,并保存items_count模型!

better to work with a counter_cache and save the items_count in the model!

scope :with_items, where("items_count > 0")


has_and_belongs_to_many :categories, :after_add=>:update_count, :after_remove=>:update_count

def update_count(category)
  category.items_count = category.items.count
  category.save
end

对于正常belongs_to的关系你只写

for normal "belongs_to" relation you just write

belongs_to :parent, :counter_cache=>true

和在parent_model你有items_count一个字段​​(项是多元化的has_many类名)

and in the parent_model you have an field items_count (items is the pluralized has_many class name)

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

在has_and_belongs_to_many关系,你必须写它作为自己的如上

in a has_and_belongs_to_many relation you have to write it as your own as above

这篇关于ActiveRecord的查找包含至少一个项的类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆