Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multi-level Associations?

I Have this setup:

Continent -> Country -> City -> Post

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 do I get all the Continents having posts trough this associations

Like:

@posts = Post.all

@posts.continents #=> [{:id=>1,:name=>"America"},{...}] 
like image 467
Mr_Nizzle Avatar asked Nov 01 '25 16:11

Mr_Nizzle


1 Answers

You can do this:

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

Or this:

class Continent < ActiveRecord::Base
  has_many :countries

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

# And then
Continent.with_post.uniq

Or this:

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

Or this:

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
like image 134
Michaël Witrant Avatar answered Nov 04 '25 10:11

Michaël Witrant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!