轨。虚拟属性(来自父模型)查询

时间:2012-08-09 19:46:37

标签: ruby-on-rails ruby activerecord

我有三种模式:帐户,会员和儿童。

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属性?

顺便说一句,我在现有的查询中有这个......

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

2 个答案:

答案 0 :(得分:1)

从Child类开始,可以这样做:

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

这可用于修改现有查询。

答案 1 :(得分: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