How are multi-level associations?

I have this setting:

ContinentCountryCityPost

and I have

class Continent < ActiveRecord::Base
   has_many :countries
end

class Country < ActiveRecord::Base
  belongs_to :continent
  has_many :cities
end

class City < ActiveRecord::Base
  belongs_to :country
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :city
end

How to get all continents with messages through these associations

how

@posts = Post.all

@posts.continents #=> [{:id=>1,:name=>"America"},{...}] 
+3
source share
1 answer

You can do it:

Continent.all(:joins => {:countries => {:cities => :posts}}).uniq

Or that:

class Continent < ActiveRecord::Base
  has_many :countries

  named_scope :with_post, :joins => {:countries => {:cities => :posts}}
end

# And then
Continent.with_post.uniq

Or that:

Post.all(:include => {:city => {:country => :continent}}).map { |post| post.city.country.continent }.uniq

Or that:

class Post < ActiveRecord::Base
  belongs_to :city

  named_scope :include_continent, :include => {:city => {:country => :continent}}

  def continent
    city.try(:country).try(:continent)
  end
end

# And then
Post.include_continent.map(&:continent).uniq
+12
source

All Articles