[英]rails association has many with multiple models
class City < ApplicationRecord
has_many :hospitals
has_many :employees
end
class Hospital < ApplicationRecord
belongs_to :city
has_many :employees
end
class Employee < ApplicationRecord
belongs_to :hospital
belongs_to :city
end
這些是我的模型。 有什么方法可以在不通過Hospital
模型中的@city
參數的情況下為醫院所在的醫院@city
員工。
hospital.rb
has_many :employees, ->(hospital_city) { where(city: hospital_city) }
這工作正常。 但我每次都需要通過hospital_city。 我想要這樣的東西。
has_many :employees, -> { #do something and return employees belongs to hospital & hospital city. }
由於員工表有city_id
, hospital_id
,所以through
不起作用
您可以在 Hospital 上定義一個方法。
class Hospital < ApplicationRecord
belongs_to :city
has_many :employees
def employees_in_city
employees.where(city: city)
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.