简体   繁体   English

Rails关联范围为“多个关联对象”

[英]Rails association scope for “more than one associated object”

Given two associated models 给定两个相关模型

class Employee < ActiveRecord::Base
  belongs_to :company
end

class Company < ActiveRecord::Base
  has_many :employees
end

How would I make a scope on "Company" so it would return any company that had more than one employee? 我如何在“公司”范围内设置范围,以使其返回拥有一名以上员工的任何公司?

Rails 3, DB is postgres. Rails 3,DB是postgres。

Thanks in advance 提前致谢

You could either add a query method like so: 您可以添加如下查询方法:

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

This would enable you to call the method like so: Customer.with_employees(2) and make the count you're comparing against dynamic (eg companies w/ more that 2 employees instead of 1). 这将使您能够像这样调用方法: Customer.with_employees(2)并进行动态比较(例如,公司的员工人数多于2,而不是1)。

Or, look at adding a counter_cache column which would then have your Employee class look like so: 或者,查看添加一个counter_cache列,该列将使您的Employee类看起来像这样:

class Employee < ActiveRecord::Base
  belongs_to :company, counter_cache: true

end

The counter_cache would require an additional column on the companies table called, employees_count , and would increment/decrement every time an employee is added/deleted. counter_cache将需要在company表上另外增加一个名为employees_count ,并且每次添加/删除员工时都会增加/减少。

The counter_cache method would decrease the SQL query impact and make it easier to query, but can be an issue maintaining it if you're adding records directly (ie not through the Rails app). counter_cache方法将减少SQL查询的影响并使其更易于查询,但是如果直接添加记录(即不通过Rails应用程序),则维护它可能是一个问题。

See this for documentation on the ActiveRecord query using 'having': http://guides.rubyonrails.org/active_record_querying.html#having 有关使用“具有”的ActiveRecord查询的文档,请参见此文件: http : //guides.rubyonrails.org/active_record_querying.html#having

And this for detail on adding a counter_cache: http://guides.rubyonrails.org/association_basics.html 有关添加counter_cache的详细信息,请参见: http : //guides.rubyonrails.org/association_basics.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM