【发布时间】:2014-06-23 09:27:07
【问题描述】:
我有两个使用people 表的模型:Person 和Person::Employee(继承自Person)。 people 表有一个 type 列。
还有另一个模型Group,它有一个称为:owner 的多态关联。 groups 表同时具有 owner_id 列和 owner_type 列。
app/models/person.rb:
class Person < ActiveRecord::Base
has_one :group, as: :owner
end
app/models/person/employee.rb:
class Person::Employee < Person
end
app/models/group.rb:
class Group < ActiveRecord::Base
belongs_to :owner, polymorphic: true
belongs_to :supervisor
end
问题是当我使用以下代码创建 Person::Employee 时,owner_type 列设置为不正确的值:
group = Group.create
=> #<Group id: 1, owner_id: nil, owner_type: nil ... >
group.update owner: Person::Employee.create
=> true
group
=> #<Group id: 1, owner_id: 1, owner_type: "Person" ... >
owner_type 应设置为"Person::Employee",但改为设置为"Person"。
奇怪的是,这在调用Group#owner 时似乎不会导致任何问题,但在创建如下关联时却会导致问题:
app/models/supervisor.rb:
class Supervisor < ActiveRecord::Base
has_many :groups
has_many :employees, through: :groups, source: :owner,
source_type: 'Person::Employee'
end
使用这种类型的关联,调用Supervisor#employees 将不会产生任何结果,因为它正在查询WHERE "groups"."owner_type" = 'People::Employees',但owner_type 设置为'People'。
为什么这个字段设置不正确,可以做些什么?
编辑:
根据this,owner_type 字段没有设置不正确,但它按设计工作并将字段设置为 base 的名称 STI 模型。
问题似乎是 has_many :through 关联搜索 Groups 并将 owner_type 设置为模型的自己的名称,而不是 base模特的名字。
设置正确查询Person::Employee 条目的has_many :employees, through: :group 关联的最佳方法是什么?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 model polymorphic-associations