通过Rails 4中的连接表使用双重多态

时间:2013-08-29 15:12:12

标签: ruby-on-rails activerecord ruby-on-rails-4 polymorphic-associations

我正在尝试使用多态来帮助减少我的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&amp; 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吗?这似乎很草率,但这是我目前唯一的想法。

1 个答案:

答案 0 :(得分:0)

如果你还想在没有STI的情况下这样做,你可以结账(即使不推荐) joins on polymorphic table