2012-08-09 53 views
1

我有三種模式:帳戶,成員和子級。Rails。虛擬屬性(來自父級模型)查詢

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 

在索引操作,我想列出所有屬於特定帳戶的孩子。我不想在children表中添加額外的account_id列。

當然,我不能做到這一點...

Child Model 
def account_id 
    self.member.account_id 
end 

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

有沒有辦法列出屬於特定帳戶的所有兒童,而無需添加account_id屬性?

順便說一句,我有這對現有的查詢......

@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 

現在,假設你有一個帳戶例如,您可以通過訪問其所有的孩子:

account.children

1

從Child類開始,可以這樣做:

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

這可以用來修改您現有的查詢。