开发者

How to filter by association count?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜