Reputation: 2055
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
These are my models. Is there any way to get employees for hospital where the hospital located without passing @city
parameter in Hospital
model.
hospital.rb
has_many :employees, ->(hospital_city) { where(city: hospital_city) }
This works fine. but I need to pass the hospital_city everytime. I want something like this.
has_many :employees, -> { #do something and return employees belongs to hospital & hospital city. }
through
not works since employee table has city_id
, hospital_id
Upvotes: 0
Views: 42
Reputation: 774
You could just define a method on Hospital.
class Hospital < ApplicationRecord
belongs_to :city
has_many :employees
def employees_in_city
employees.where(city: city)
end
end
Upvotes: 1