开发者

How to filter by association count?

开发者 https://www.devze.com 2022-12-08 05:45 出处:网络
Let\'s say I have models that look like this: class Foo < ActiveRecord::Base has_man开发者_Go百科y :bars, :through => :cakes

Let's say I have models that look like this:

class Foo < ActiveRecord::Base
    has_man开发者_Go百科y :bars, :through => :cakes
    has_many :cakes
end

class Bar < ActiveRecord::Base
    has_many :foos, :through => :cakes
    has_many :cakes
end

class Cake < ActiveRecord::Base
    belongs_to :foo
    belongs_to :bar
end

How would I get all foos which had 10 or more bars (and therefore 10 or more cakes)?


Foo.all(:joins => :cakes, 
  :group => "cakes.foo_id", 
  :having => "count(cakes.bar_id) >= 10")


okay i tried the answer above, but had a problem.

for our purposes Father has_many :sons, ok?

i wanted to find Fathers that had zero sons.

the above did not work, because it produced an inner join... thereby filtering out all fathers without sons.

the following did work for me:

Father.includes(:sons).group('fathers.id').having( 'count(sons.id)=0' )

and it also happens to work for any other filter you'd require

Father.includes(:sons).group('fathers.id').having( 'count(sons.id)=3' )

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号