Home > Net >  RSpec Rails PG::UndefinedColumn: ERROR: column <table>.<another_class_name>_type does no
RSpec Rails PG::UndefinedColumn: ERROR: column <table>.<another_class_name>_type does no

Time:02-20

I have three models associated the following way:

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

Then:

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

Last:

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

There is no polymorphic association between these classes

The models run fine except when I try to test them with RSpec. If I try to to print for instance the ownerships of A with pp a.ownerships, it will complain that:

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

I simply do not get it...

CodePudding user response:

The as: option is exclusively used to setup polymorphic assocations which is why ActiveRecord is creating a query for an owner_type column. Its not needed here.

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