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_idchildren

当然,我不能这样做……

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)
4

2 回答 2

1

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

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

这可用于修改您现有的查询。

于 2012-08-09T20:42:51.663 回答
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

现在假设您有一个 accounts 实例,您可以通过以下方式访问它的所有子实例:

account.children

于 2012-08-09T20:36:32.560 回答