【发布时间】:2013-08-29 15:12:11
【问题描述】:
我正在尝试使用多态性来帮助减少我的 Rails 4 应用程序中的重复,但运气不佳。从概念上讲,我有计算机和打印机,我认为这两者都可以被视为设备。这些项目分配给员工或设施,两者都作为所有者。我还需要跟踪监管链,所以我认为只需将一些日期时间字段添加到连接表中就可以让我完成我想要的一切。
到目前为止的代码:
class Facility < ActiveRecord::Base
has_many :computers, as: :equipment
has_many :printers, as: :equipment
belongs_to :owners, polymorphic: true
end
class Employee < ActiveRecord::Base
has_many :computers, as: :equipment
has_many :printers, as: :equipment
belongs_to :owners, polymorphic: true
end
class Computer < ActiveRecord::Base
belongs_to :equipment, polymorphic: true
has_many :facilities, as: :owners
has_many :employees, as: :owners
end
class Printer < ActiveRecord::Base
belongs_to :equipment, polymorphic: true
has_many :facilities, as: :owners
has_many :employees, as: :owners
end
# Join table structure
create_table "equipment_owners", force: true do |t|
t.integer "equipment_id"
t.string "equipment_type"
t.integer "owner_id"
t.string "owner_type"
t.datetime "possession_datetime"
t.datetime "relinquish_datetime"
t.datetime "created_at"
t.datetime "updated_at"
end
关于如何使用多态关联的大多数示例都是单数的(即Rails guide 和Railscast #154),因此我尽量遵循这些结构。不幸的是,在 Rails 控制台中测试关联显示错误:
irb > Computer.find_by_id(9).facilities
Facility Load (0.2ms) SELECT "facilities".* FROM "facilities" WHERE "facilities"."owners_id" = ? AND "facilities"."owners_type" = ? [[nil, 9]]
SQLite3::SQLException: no such column: facilities.owners_id: SELECT "facilities".* FROM "facilities" WHERE "facilities"."owners_id" = ? AND "facilities"."owners_type" = ?
这表明我需要告诉 ActiveRecord 查看 EquipmentOwners 表。不幸的是,如果我将 has_many 更新为 has_many :facilities, as: :owners, through: :equipment_owners,我会收到以下错误:
irb > Computer.find_by_id(9).facilities
Computer Load (0.4ms) SELECT "computers".* FROM "computers" WHERE "computers"."id" = 9
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :equipment_owners in model Computer
任何人都可以提出一种方法来完成这项工作,或者这只是超出了我使用标准 Rails 关联所能做的吗?在我的所有表格中创建equipment_owner_id 的答案是什么?这似乎很草率,但这是我目前唯一的想法。
【问题讨论】:
-
即使模型与上面列出的不同?每个多态组中数据字段的重叠是最小的,即使它们最终与相反组具有相似的关系。
标签: ruby-on-rails activerecord ruby-on-rails-4 polymorphic-associations