2009-10-14 87 views
3

比方說,我有模型,如下所示:如何按關聯計數過濾?

class Foo < ActiveRecord::Base 
    has_many :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 

我怎麼會得到所有的Foo其中有10個或更多的酒吧(因此10分或更多的蛋糕)?

回答

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

可以加快這counter_cache。 Foo.find(:all,:conditions => ['foo.cake_count> 10']) – jonnii 2009-10-14 04:38:27

1

好吧我試過上面的答案,但有一個問題。

我們的目的父親has_many:兒子,好嗎?

我想找到沒有兒子的父親。

上述不起作用,因爲它產生了一個內部連接......從而過濾掉所有沒有兒子的父親。

以下爲我所做的工作:

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

,它也恰好用任何其他過濾器的工作你需要

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