我正在尝试使用关联表以及单表继承('STI')。我有一个男人、女人和一个关系模型。关系模型有一个类型列,因此我可以使用 STI。我还创建了一个继承自 Relationship 的 Friend 模型,因为 Friend 将是一种关系。
曼.rb
attr_accessible :name
has_many :relationships
has_many :women, :through => :relationships
女人.rb
attr_accessible :name
has_many :relationships
has_many :men, :through => :relationships
在聚会模型中,我还希望跟踪日期发生的时间和地点。
关系.rb
attr_accessible :type
belongs_to :woman
belongs_to :man
朋友.rb
class Friend < Relationship
end
但是,当我尝试与类型朋友创建关系时,我收到子类不存在的警告消息。在控制台中,我正在这样做
sarah = Woman.create!(name: 'Sarah')
jim = Man.create!(name: 'Jim')
jim.relationships.build(type: 'Friend', woman_id: 1)
=> #<Relationship id: nil, type: "Friend", man_id: 1, woman_id: 1, created_at: nil, updated_at: nil>
jim.save!
但是当我试图为吉姆拉起关系时,我得到了
>> jim.relationships
Relationship Load (0.3ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."man_id" = 1
ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'friends'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Relationship.inheritance_column to use another column for that information.
当我尝试与“朋友”而不是“朋友”建立关系时也是如此
jim.relationships.build(type: 'friends', woman_id: 1)
你能解释一下我做错了什么吗?
我没有在数据库中为朋友创建表。我认为一切都可以存储在关系模型中。由于这只是一个游戏应用程序,我只为关系模型分配了 type 属性。