RSpec Rails PG::UndefinedColumn: ERROR: column <table>.<another_class_name>_type does not exist

RSpec Rails PG::UndefinedColumn: ERROR: column <table>.<another_class_name>_type does not exist

我通过以下方式关联了三个模型:

class A < ApplicationRecord
  has_many :ownerships, as: :owner, inverse_of: :owner, foreign_key: :owner_id
  has_many :cs, through: :ownerships

然后:

class Ownership < ApplicationRecord
  belongs_to :owner, class_name: 'A', foreign_key: :owner_id, inverse_of: :ownerships
  belongs_to :c, inverse_of: :ownership

最后一个:

class C < ApplicationRecord
  has_one :ownership, inverse_of: :c
  has_one :owner, class_name: 'A', through: :ownership

这些之间没有多态关联类

模型 运行 很好,除非我尝试用 RSpec 测试它们。 例如,如果我尝试使用 pp a.ownerships 打印 A 的所有权,它会抱怨:

ActiveRecord::StatementInvalid:
  PG::UndefinedColumn: ERROR:  column ownerships.owner_type does not exist
  LINE 1: ...wnerships" WHERE "ownerships"."owner_id" =  AND "ownership...

我就是不明白...

as: 选项专门用于设置 polymorphic assocations,这就是 ActiveRecord 为 owner_type 列创建查询的原因。这里不需要。

class A < ApplicationRecord
  has_many :ownerships, 
    inverse_of: :owner,
    foreign_key: :owner_id
  has_many :cs, through: :ownerships
end