Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 通过Rails 4中的联接表使用双重多态性_Ruby On Rails_Activerecord_Ruby On Rails 4_Polymorphic Associations - Fatal编程技术网

Ruby on rails 通过Rails 4中的联接表使用双重多态性

Ruby on rails 通过Rails 4中的联接表使用双重多态性,ruby-on-rails,activerecord,ruby-on-rails-4,polymorphic-associations,Ruby On Rails,Activerecord,Ruby On Rails 4,Polymorphic Associations,我试图使用多态性来帮助减少Rails 4应用程序中的重复,但运气不太好。从概念上讲,我有电脑和打印机,我认为这两种都可以被视为设备。这些项目分配给员工或设施,两者都是所有者。我还需要跟踪保管链,所以我认为只需在联接表中添加一些datetime字段,就可以实现我想要的一切 迄今为止的代码: class Facility < ActiveRecord::Base has_many :computers, as: :equipment has_many :printers, a

我试图使用多态性来帮助减少Rails 4应用程序中的重复,但运气不太好。从概念上讲,我有电脑和打印机,我认为这两种都可以被视为设备。这些项目分配给员工或设施,两者都是所有者。我还需要跟踪保管链,所以我认为只需在联接表中添加一些datetime字段,就可以实现我想要的一切

迄今为止的代码:

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
这表明我需要告诉ActiveRecord查看EquipmentOwners表。不幸的是,如果我通过::设备所有者更新我的has\u many to
has\u many:facility,as::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协会所能做到的吗?在我的所有表格中都要填写
设备\u所有者\u id
?这似乎有点草率,但这是我目前唯一的想法。

如果你仍然想在没有STI的情况下这样做,你可以结帐(即使不建议这样做)

您需要STI,即使与上面列出的型号不同?每个多态组中的数据字段重叠最小,即使它们最终与另一组具有相似的关系。
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