2

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 ?

Bharat soni
  • 2,686
  • 18
  • 27
Ugo Mare
  • 442
  • 5
  • 15

3 Answers3

5

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

Rodrigo
  • 5,435
  • 5
  • 42
  • 78
0

From @Octopus-Paul:

Country.all.map {|country| country.regions }.flatten
Ugo Mare
  • 442
  • 5
  • 15
0

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

countries = Country.all
regions = Region.where(country: countries)
Edison Arango
  • 948
  • 12
  • 14