我有一个有很多孩子的简单父对象.我正在试图弄清楚如何使用命名范围来恢复具有特定数量的孩子的父母.
这可能吗?
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这样的事情
解决方法
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,:having => ["count(bars.foo_id) = ?",n]}} named_scope :with_gt_n_bars,:having => ["count(bars.foo_id) > ?",n]}} end
像这样打电话:
Foo.with_n_bars(2)