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"},{...}]
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
精彩评论