davhab
davhab

Reputation: 805

Rails: How to retrieve a model's has_many objects as collection?

Let's say I have something like

Country has_many :cities

and the model City has an attribute council_id. Only having an instance of Country, what is the best way to retrieve a collection that contains all the relevant Councils?

I know this can be easily done passing the Country instance to some method and iterating over the council_ids but I was wondering if there is a more elegant way?

Thanks

Upvotes: 1

Views: 141

Answers (3)

Frederick Cheung
Frederick Cheung

Reputation: 84114

If city has

belongs_to :country
belongs_to :council

Then country can have

has_many :cities
has_many :councils, :through => :cities

And then you can do some_country.councils. Behind the scenes this constructs a join query to load the associated councils. This would still work if a city had many councils - has_many :through can figure that out

Upvotes: 5

lee
lee

Reputation: 2439

This is the shortest way I can think of (assumes you have set the @country instance):

Council.joins(:city => :countries).where('countries.id = ?', @country.id)

You may want to just save the country_id for each Council though to make this easier with:

@country.councils

Upvotes: 0

Aleksey Bakin
Aleksey Bakin

Reputation: 1536

If Council is model, try following:

Council.where(city_id: @country.cities)

If council_id is attribute of City model:

@country.cities.map {|c| c.council_id}

Upvotes: 0

Related Questions