2011-05-09 5 views
3

나는이 설치 유무 : ->Country ->City -다중 레벨 연관성은 어떻습니까?

Continent>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"},{...}] 

답변

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

그냥 완벽한 남자! –

+0

굉장! ActiveRecord에 중첩 된 조인을 할 수있는 내장 옵션이 있다는 것을 알지 못했습니다! :) –

+0

hmmm, 구문 오류가 발생했습니다. '잘못된 인수 (주어진 1, 예상 된 0)'나는 인터페이스가 수년간 바뀌 었다고 가정합니다. 검색 계속 ... –

관련 문제