我有这些模型:
class User < ActiveRecord::Base
has_many :managements, class_name: 'Management', foreign_key: :manager_id
has_many :primary_locations, -> { where managements:
{ manager_role: "primary" } }, through: :managements,
source: :manageable, source_type: 'Location'
has_many :secondary_locations, -> { where managements:
{ manager_role: "secondary" } }, through: :managements,
source: :manageable, source_type: 'Location'
has_many :primary_departments, -> { where managements:
{ manager_role: "primary" } }, through: :managements,
source: :manageable, source_type: 'Department'
has_many :secondary_departments, -> { where managements:
{ manager_role: "secondary" } }, through: :managements,
source: :manageable, source_type: 'Department'
end
用户可以管理多个部门和地点,并且可以是每个部门的主要或次要经理:
class Management < ActiveRecord::Base
belongs_to :manager, class_name: 'User', foreign_key: :manager_id
belongs_to :manageable, polymorphic: true
end
class Location < ActiveRecord::Base
has_many :managements, class_name: "Management", foreign_key: :manageable_id,
as: :manageable
has_many :primary_managers, -> { where management:
{ manager_role: "primary" } }, through: :managements, source: :manager
has_many :secondary_managers, -> { where management:
{manager_role: "secondary"} }, through: :managements, source: :manager
end
class Department < ActiveRecord::Base
has_many :managements, class_name: "Management", foreign_key: :manageable_id,
as: :manageable
has_many :primary_managers, -> { where management:
{ manager_role: "primary" } }, through: :managements, source: :manager
has_many :secondary_managers, -> { where management:
{manager_role: "secondary"} }, through: :managements, source: :manager
end
当我调用时,以下关联会产生错误user.primary_departments
:
SELECT "departments".* FROM "departments" INNER JOIN "managements" ON
"departments"."id" = "managements"."manageable_id" WHERE
"managements"."manager_role" = 'primary' AND "managements"."manager_id" = $1
AND "departments"."manageable_type" = 'Department' [["manager_id", 1]]
PG::UndefinedColumn: ERROR: column department.manageable_type does not exist
location.primary_managers
协会工作。所以它似乎几乎可以工作,除了多态类型指向错误的表。我如何指定在桌子manageable_type
上找到的?management