我如何撰寫一個rails范圍,以回傳Company的所有實體,其中其Employees狀態都是'active'?
classEmployee < ApplicationRecord
STATUS = ['active', 'busy', 'inactive']
belongs_to: :company ]
結束
class Company < ApplicationRecord
has_many: :員工
end
我嘗試了以下范圍 :
scope :with_active_employees_only, -> {
select("DISTINCT ON (companies.id) companies.*"/span>)
.joins(:employees)
.where("employees.status NOT IN (?)", Employee::STATUS - ['active'])
}
但是它仍然回傳給我一些員工是'busy'或'inactive'的公司,盡管我只想要那些員工是完全'active'的公司。我怎樣才能實作這一點呢?
uj5u.com熱心網友回復:
includes(:employees).where(employees: { status: 'active'/span> })
uj5u.com熱心網友回復:
如果你在最新的6.1.x版本的activerecord上,你可以使用where.missing與一個恰當的構建關聯:
class Company>
has_many :inactive_employees, -> { where(status: 'inactive') },
class_name: 'Employee', inverse_of: nil.
#包括完全沒有雇員的公司。
scope :without_inactive_employees, -> {
where.missing(:inactive_employees)
}
end。
如果你不在那里,你仍然可以從https://github.com/rails/rails/blob/6-1-stable/activerecord/lib/active_record/relation/query_methods.rb#L71-L80
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/322165.html
標籤:
