0

我正在尝试使用多态性来帮助减少 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在我所有的桌子上做一个吗?这似乎草率,但这是我目前唯一的想法。

4

1 回答 1

0

如果您仍然想在没有 STI 的情况下这样做,您可以在多态表上结帐(即使不推荐) 连接

于 2013-12-24T14:30:16.087 回答