【问题标题】:How to get all children of a particular type in a polymorphic association如何在多态关联中获取特定类型的所有孩子
【发布时间】:2013-09-07 07:42:38
【问题描述】:

我写了一个可行的方法,但感觉不优雅。我想知道我是否错过了更好的方法。

我有一个这样设置的多态关联;

class Employee < ActiveRecord::Base
  has_many :phones, as: :phoneable
end

class Client < ActiveRecord::Base
  has_many :phones, as: :phoneable
end

class Phone < ActiveRecord::Base
  belongs_to :phoneable, polymorphic: true
end

我的电话表有标准的phoneable_id:integerphoneable_type:string 列。

我想要做的是为之前选定的一组员工获取所有电话,例如

employees = Employee.where role: 'peon'

如果这是一个正常的has_many 关系,我会将我的电话查询写为;

Phone.where employee_id: employees

为了在多态关系中执行此操作,我将查询编写为;

Phone.where phoneable_type: 'employee', phoneable_id: employees

这可行,但我觉得应该有比明确声明phoneable_type 更好的方法。 Rails 是否有办法在出现一组员工时自动执行此操作,还是我为简单起见而过度使用?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord rails-activerecord polymorphic-associations


    【解决方案1】:

    您不了解多态关联的全部重要性。如果您在模型中定义了它,您可以轻松获取如下记录:

    假设您在员工表中有一个“Peon”角色:

    @employee = Employee.where(role: 'peon').first
    

    现在您可以像这样获取记录:

     @employee.phones
    

    如果您想获取具有“peon”角色的员工的所有电话,您可以这样做:

    @employees = Employee.where(role: 'peon')   
    
    @peon_phones = @employees.map{|x| x.phones}
    

    在客户端的情况下也是如此:

    @client = Client.first
    
    @client.phones
    

    它和你想象的一样简单。希望它会有所帮助。谢谢

    【讨论】:

    • 是的,除了使用这样的 map 会导致大量的数据库请求并且可能非常慢。我一直在寻找仅数据库的解决方案。
    【解决方案2】:

    为了通过 Rails 5 中的单个查询来完成此操作(自这个问题以来已经出现),您可以这样做:

    Phone.where(phoneable: employees) 
    

    Rails 将能够从 employees 集合中的对象推断 id 和类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多