给定两个相关模型
class Employee < ActiveRecord::Base
belongs_to :company
end
class Company < ActiveRecord::Base
has_many :employees
end
我如何在"公司"上创建一个作用域,以便它将返回具有多于一个员工的任何公司?
Rails 3,数据库是postgres
Thanks in advance
您可以添加如下查询方法:
class Company < ActiveRecord::Base
has_many :employees
def self.with_employees(cnt = 1)
select('companies.*, count(employees.id) as employee_count')
.joins(:employees)
.group('companies.id')
.having('count(employees.id) > ?', cnt)
end
end
这将使您能够像这样调用方法:Customer.with_employees(2)
并使您正在比较的计数与动态(例如,拥有2名员工而不是1名员工的公司)。
或者,看看添加一个counter_cache列,然后让你的Employee类看起来像这样:
class Employee < ActiveRecord::Base
belongs_to :company, counter_cache: true
end
counter_cache将需要在companies表上增加一个名为employees_count
的列,并且在每次添加/删除员工时增加/减少。
counter_cache方法将减少SQL查询的影响,使其更容易查询,但如果你直接添加记录(即不通过Rails应用程序),维护它可能是一个问题。
查看使用'having'查询ActiveRecord的文档:http://guides.rubyonrails.org/active_record_querying.html有
下面是关于添加counter_cache的详细信息:http://guides.rubyonrails.org/association_basics.html