【问题标题】:Rails. Virtual attribute (from a parent model) query导轨。虚拟属性(来自父模型)查询
【发布时间】:2012-08-09 19:46:37
【问题描述】:

我有三个模型:Account、Member 和 Child。

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)

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:
      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

      【讨论】:

        猜你喜欢
        • 2016-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多