【发布时间】: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:integer 和phoneable_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