如何进行多级关联?

Mr_*_*zle 3 activerecord associations ruby-on-rails-3

我有这个设置:

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
Run Code Online (Sandbox Code Playgroud)

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

喜欢:

@posts = Post.all

@posts.continents #=> [{:id=>1,:name=>"America"},{...}] 
Run Code Online (Sandbox Code Playgroud)

Mic*_*ant 12

你可以这样做:

Continent.all(:joins => {:countries => {:cities => :posts}}).uniq
Run Code Online (Sandbox Code Playgroud)

或这个:

class Continent < ActiveRecord::Base
  has_many :countries

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

# And then
Continent.with_post.uniq
Run Code Online (Sandbox Code Playgroud)

或这个:

Post.all(:include => {:city => {:country => :continent}}).map { |post| post.city.country.continent }.uniq
Run Code Online (Sandbox Code Playgroud)

或这个:

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
Run Code Online (Sandbox Code Playgroud)