[英]Creating a SCOPE for an association with more than 3 models - Rails 4
[英]Rails association scope for “more than one associated object”
給定兩個相關模型
class Employee < ActiveRecord::Base
belongs_to :company
end
class Company < ActiveRecord::Base
has_many :employees
end
我如何在“公司”范圍內設置范圍,以使其返回擁有一名以上員工的任何公司?
Rails 3,DB是postgres。
提前致謝
您可以添加如下查詢方法:
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將需要在company表上另外增加一個名為employees_count
,並且每次添加/刪除員工時都會增加/減少。
counter_cache方法將減少SQL查詢的影響並使其更易於查詢,但是如果直接添加記錄(即不通過Rails應用程序),則維護它可能是一個問題。
有關使用“具有”的ActiveRecord查詢的文檔,請參見此文件: http : //guides.rubyonrails.org/active_record_querying.html#having
有關添加counter_cache的詳細信息,請參見: http : //guides.rubyonrails.org/association_basics.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.