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



我有三个模型:帐户,会员和子。

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)

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

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

这可用于修改现有查询。

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

相关内容

  • 没有找到相关文章

最新更新