ruby-on-railsrubyhas-manyglobalize3globalize

Get an array of many objects associations


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 ?


Solution

  • 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