本文介绍了将 named_scope 与子模型的计数一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的父对象,有很多子对象.我正在尝试弄清楚如何使用命名范围来仅带回具有特定数量孩子的父母.
I have a simple parent object having many children. I'm trying to figure out how to use a named scope for bringing back just parents with specific numbers of children.
这可能吗?
class Foo < ActiveRecord::Base
has_many :bars
named_scope :with_no_bars, ... # count of bars == 0
named_scope :with_one_bar, ... # count of bars == 1
named_scope :with_more_than_one_bar, ... # count of bars > 1
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
我希望做一些像 Foo.with_one_bar
我可以在父类上为这样的事情编写方法,但我宁愿拥有命名范围的力量
I could write methods on the parent class for something like this, but I'd rather have the power of the named scope
推荐答案
class Foo < ActiveRecord::Base
has_many :bars
# I don't like having the number be part of the name, but you asked for it.
named_scope :with_one_bar, :joins => :bars, :group => "bars.foo_id", :having => "count(bars.foo_id) = 1"
# More generically...
named_scope :with_n_bars, lambda {|n| {:joins => :bars, :group => "bars.foo_id", :having => ["count(bars.foo_id) = ?", n]}}
named_scope :with_gt_n_bars, lambda {|n| {:joins => :bars, :group => "bars.foo_id", :having => ["count(bars.foo_id) > ?", n]}}
end
这样称呼:
Foo.with_n_bars(2)
这篇关于将 named_scope 与子模型的计数一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!