如何通过关联计数过滤?

igu*_*222 3 sql activerecord ruby-on-rails

假设我的模型看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到10个或更多棒(因此有10个或更多个蛋糕)的所有foos?

pjb*_*jb3 5

Foo.all(:joins => :cakes, 
  :group => "cakes.foo_id", 
  :having => "count(cakes.bar_id) >= 10")
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用counter_cache加快速度.Foo.find(:all,:conditions => ['foo.cake_count> 10']) (4认同)