Using named_scope with counts of child models

后端 未结 2 1296
刺人心
刺人心 2020-12-16 07:12

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.

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 07:54

    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
    

    Called like so:

    Foo.with_n_bars(2)
    

提交回复
热议问题