2012-08-09 6 views
1

계정, 회원 및 자녀의 세 가지 모델이 있습니다.레일. 부모 모델의 가상 속성 쿼리

Member belongs to Account 
Child belongs to Member 

회원 인덱스 동작에서, ACCOUNT_ID이없는 아이 ACCOUNT_ID 속성

그래서 나는이 작업을 수행 할 수있는 속성 ...

Member.where(:account_id => current_user.account.id) 

c = Child.last 
c.member.account_id 

을 가지고, 나는 나열 할 특정 계정에 속한 모든 어린이. account_id 열을 children 테이블에 추가하고 싶지 않습니다. 나는이 작업을 수행 할 수 물론

...

Child Model 
def account_id 
    self.member.account_id 
end 

Children Controller 
Child.where(:account_id => current_user.account.id) 

account_id 속성을 추가 할 필요없이 특정 계정에 속한 모든 어린이를 나열하는 방법이 있나요?

account.children : 그런데

, 나는 지금 당신은 당신이에 의해 모든 자식에 액세스 할 수있는 계정의 인스턴스가 가정

@children = Child.search(params[:search]).order(sort_column + ' ' + sort_direction).page(params[:page]).per(10) 

답변

0
class Account < ActiveRecord::Base 
    has_many :members 
    #This is the line you were looking for 
    has_many :children, :through => :members 
end 

class Member < ActiveRecord::Base 
    belongs_to :account 
    has_many :children, :class_name => "Child" 
end 

class Child < ActiveRecord::Base 
    belongs_to :member 
end 

... 기존 쿼리에이이

1

하위 클래스부터 시작하면 다음과 같이 할 수 있습니다.

Child.includes(:member).where(:'members.account_id' => current_user.account.id) 

기존 쿼리를 수정하는 데 사용할 수 있습니다.