Reputation: 452
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 ?
Upvotes: 2
Views: 1190
Reputation: 1066
Just search for the regions that match your list of countries:
countries = Country.all
regions = Region.where(country: countries)
Upvotes: 0
Reputation: 4802
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
Upvotes: 5
Reputation: 452
From @Octopus-Paul:
Country.all.map {|country| country.regions }.flatten
Upvotes: 0