2011-05-09 78 views
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 

如何获得各大洲有帖子低谷这个协会

Like:

@posts = Post.all 

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

回答

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 
+1

只是完美男人! – 2011-05-10 04:27:30

+0

太棒了!不知道有一个内置选项在ActiveRecord中进行嵌套连接! :) – 2013-10-02 13:41:54

+0

嗯,我得到一个语法错误'错误的参数数量(给定1,预计0)'我想接口已经改变了多年。搜索继续... – 2017-11-13 05:48:54