Reputation: 655
This question must have been asked million times already, but i just couldn't find the answer :(
Assuming I have 3 models:
class Country
has_many :cities
end
class City
has_many :companies
end
class Company
belongs_to :city
end
I can fetch companies in the given City by City.first.companies
, but what I would like is to be able to fetch all companies for given Country, like Country.first.companies
What I was able to achieve is to write a method in Country
model:
def companies
@companies = []
cities.all.each{ |c| @companies << c.companies unless c.companies.empty? }
@companies
end
But it returns array of arrays of Company objects. I could have also added country_id
column as a FK for Country model, like
class Country
has_many :cities
has_many :companies
end
class Company
belongs_to :city
belongs_to :country
end
but that doesn't look very DRY.
I would like to receive array of Company objects for given Country. I'm pretty sure that there is a Rails way to achieve this. What would it be?
Thanks!
Upvotes: 0
Views: 76
Reputation: 15089
Use the has_many through
association.
class Country
has_many :companies, :through => :cities
Now you can use Country.last.companies
.
Upvotes: 1