如何进行多级关联?

时间:2011-05-09 22:05:57

标签: ruby-on-rails-3 activerecord associations

我有这个设置:

Continent - > Country - > City - > Post

我有

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

如何通过此关联让所有大陆发布帖子

像:

@posts = Post.all

@posts.continents #=> [{:id=>1,:name=>"America"},{...}] 

1 个答案:

答案 0 :(得分:12)

你可以这样做:

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

或者这个:

class Continent < ActiveRecord::Base
  has_many :countries

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

# And then
Continent.with_post.uniq

或者这个:

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

或者这个:

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