2012-12-20 2 views
2

그래서 페이지와 앱 및 앱 콘텐츠 시스템을 설정하고 있습니다. 페이지 has_many : app_instances 및 app_instances has_many : app_contents. 페이지, 앱 app_instance, app_content 내 모델에서ActiveRecord : 다른 has_many 안에 Has_many - rails3과 함께

:

나는 모델을 가지고

class Page < ActiveRecord::Base 
    has_many :app_instances 
end 

class App < ActiveRecord::Base 
    belongs_to :page 
end 

class AppInstance < ActiveRecord::Base 
    belongs_to :page 
    belongs_to :app 
    has_many :app_contents 
end 

class AppContent < ActiveRecord::Base 
    belongs_to :app_instance 
    belongs_to :app 
end 

내가 모든 내용은 개별 내용 살고 아래에 하나의 개체를 가지고 싶습니다 애플 리케이션 인스턴스 아래에 ...하지만이 일을 할 수있는 방법이 있습니까? 내 컨트롤러 중 하나에

I 설정이 :

@page = Page.includes(:app_instances).find(params[:id]) 

내가 성공적으로 page.app_instances @ 디버깅 할 수 있습니다,하지만 난 page.app_instances.app_contents @ 말한대로 곧 내가 오류가 발생합니다. 나는 이것이 내가 그 "좋은 연습"

, 또는 경우에도 내가 아마 할 수있는 알고 쓰기 내가 어떻게 확인을 포함 내에 포함 누락,하지만 오전해서 추측하고있다 :

has_many :app_contents, :through => :app_instances 

하지만 id는 오히려 내용을 담고있는 인스턴스로 구성된 객체를 가지고 있습니다. (맞습니까?) ... 그래서 모든 인스턴스를 순환하여 인스턴스의 내용을 출력 할 수 있습니다.

내 DB 아키텍처 이해가 되니? 또는 나는이에 잘못된 방향으로 가고있다

조엘

답변

1

다음을 사용하여 중첩 포함 할 수있다 : @page.app_instances.app_contents page.app_instances에 '아무튼 때문에 오류를 얻고있다

Page.includes(:app_instances=>[:app_contents]) 

그러나 주된 이유는 t는 app_contents입니다. 당신은 모든 app_instances

@page의의 app_contents의 조합을 찾는 것입니다 그래서를 통해 수행 할 수 있습니다 :

@page.app_instances.app_contents.each{|ai| (list || =[]) << ai.app_contents} 
list.flatten! 

또는

이 모델의 page has many app_contents through app_instances 관계를 정의합니다.

첫 번째 경우, app_instances에 대한 쿼리를 실행하지만 앞에서 그 단일 쿼리 초래 언급 한 바와 같이 를 사용하여를 포함와 것입니다. 두 번째 경우는 app_contents, app_instances 테이블에 가입하는 단일 조인 쿼리가됩니다.

+0

has_many, through가 최상의 접근 방법이라고 생각하십니까? –

+0

예. .. 그것은 페이지 및 app_contents 의 최상의 관계를 정의하고 쿼리가 실제로 더 최적화되었습니다 .. –