2012-10-25 4 views
1

이미지가 내 데이터 모델의 일부를 보여줍니다. 조직 및 items_group을 통해 사용자와 관련된 모든 항목을 가져 오려고합니다. 모델을 어떻게 변경하고 컨트롤러에서이 쿼리를 작성해야합니까? Using : through => organizations 모든 items_groups를 얻을 수는 있지만 관련 항목을 쿼리하기 위해 하나의 관계를 추가하는 방법은 없습니다.여러 테이블을 통해 레코드를 가져 오는 중

users.organizations.item_groups.items 

비록 그것을이 포함되어야 모델을 작동하려면 :

class User < ActiveRecord::Base   
    has_many :organizations, :through => :organization_users 
end 

class Organization < ActiveRecord::Base 
    has_many :item_groups, :through => :items_groups_organizations 
end 

class ItemsGroup < ActiveRecord::Base 
    belongs_to :item 
end 

희망을 당신이 관계는이 작업을해야합니다 귀하의 모델 설정하면

enter image description here

class User < ActiveRecord::Base   
    has_and_belongs_to_many :organizations 
    has_many :items_groups, :through => :organizations   
end 

class Organization < ActiveRecord::Base 
    has_and_belongs_to_many :users 
    has_and_belongs_to_many :items_groups 
    has_many :items, :through => :items_groups 
end 

class ItemsGroup < ActiveRecord::Base 
    has_many :items, :inverse_of => :items_group 
    has_and_belongs_to_many :organizations 
    has_many :users, :through => :organizations    
end 

답변

4

나는 당신이 그것을 앞 다투어해야 할 것이라고 생각하고 항목을 다시 사용자에게 보냈습니다.

당신은 당신의 사용자 클래스에서이 같은 방법을 정의 할 수 있습니다 :

def items 
    Item.joins(:items_group => {:organizations => :users}).where("users.id" => self.id).select("distinct items.*") 
end 

이 때문에 명시 적 select의 읽기 전용하지만 난 당신이 개별 항목 이상을 반환하지 않도록 할 수있을 거라 생각됩니다 반환 항목을 한번 이상.

+0

일했습니다! 고마워요 ... – migu

0

그것은 당신을 위해 일합니다!

+0

나는 그것이 작동한다고 확신하지 않습니다. 나는'organization'에서'item_groups'를 호출하려고 할 때 오류가 발생한다고 생각합니다. 너에게 효과가 있니? – Shadwell

+0

has_and_belongs_to_many를 사용할 때 (왜냐하면 나는 조인트 테이블을위한 모델을 생성 할 필요가 없습니다) 레일 3.2.8에서 이것을 얻었습니다 : NoMethodError 예외 : # 에 대해'items_groups '메소드가 정의되지 않았습니다. – migu

관련 문제