Get an array of many objects associations

1.1k Views Asked by At

I didn't know exactly how to find an understandable title so I'll try my best to explain my problem.

I have 2 models: - Country translatable with globalize, with a name and many regions - Region belongs_to country

What I would like to do is geting an array of all regions form an array of countries.

E.g.

Country.all.regions
Country.with_translations(I18n.locale).order("country_translations.name asc").regions

There is an easy way to get this array ?

3

There are 3 best solutions below

2
Rodrigo On BEST ANSWER

The @Octopus-Paul solution works, but it has n+1 queries problem. To avoid it, use the includes method.

Country.includes(:regions).all.map {|country| country.regions }.flatten

Read more here: http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

0
Ugo Mare On

From @Octopus-Paul:

Country.all.map {|country| country.regions }.flatten
1
Edison Arango On

Just search for the regions that match your list of countries:

countries = Country.all
regions = Region.where(country: countries)