ruby-on-railsactiverecordsti

rails multiple STI relation has_many


I have theses models

class OfferWrapper < ApplicationRecord

end

class PurchaseOfferWrapper < OfferWrapper
  has_many :purchase_offers, dependent: :destroy
end

class Offer < ApplicationRecord
end

class PurchaseOffer < Offer
  belongs_to :purchase_offer_wrapper, foreign_key: :offer_wrapper_id, inverse_of: :purchase_offer
end

My migration

def change
  create_table :offer_wrappers do |t|
    t.string :ref
    t.timestamp
  end
  add_reference :offers, :offer_wrapper
end

but when I try to access to a purchase_offer from a purchase_offer_wrapper i have a foreign_ky error like this

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column offers.purchase_offer_wrapper_id does not exist
LINE 1: ...s" WHERE "offers"."type" IN ('PurchaseOffer') AND "offers"."...
                                                             ^
: SELECT COUNT(*) FROM "offers" WHERE "offers"."type" IN ('PurchaseOffer') AND "offers"."purchase_offer_wrapper_id" = $1

[4] pry(main)> PurchaseOfferWrapper.last.purchase_offers.to_sql
  PurchaseOfferWrapper Load (0.6ms)  SELECT  "offer_wrappers".* FROM "offer_wrappers" WHERE "offer_wrappers"."type" IN ('PurchaseOfferWrapper') ORDER BY "offer_wrappers"."id" DESC LIMIT $1  [["LIMIT", 1]]
=> "SELECT \"offers\".* FROM \"offers\" WHERE \"offers\".\"type\" IN ('PurchaseOffer') AND \"offers\".\"purchase_offer_wrapper_id\" = 4806"

I use foreign_key option in my belongs_to to force offer_wrapper_id , but it dosen't work. it still try to use purchase_offer_wrapper_id.

Where is my mistake ?

Thanks in avdance


Solution

  • Okay, finaly I found the problem.

    I have to add foreign_key option in my has_many association too.

    class PurchaseOfferWrapper < OfferWrapper
      has_many :purchase_offers, foreign_key: :offer_wrapper_id, dependent: :destroy
    end