ruby-on-rails 轨道多个STI关系has_many

ztmd8pv5  于 2023-04-22  发布在  Ruby
关注(0)|答案(1)|浏览(230)

我有这些模型

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

我的迁徙

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

但是当我尝试从purchase_offer_wrapper访问purchase_offer时,我遇到了这样的foreign_ky错误

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"

我在我的belongs_to中使用foreign_key选项来强制offer_wrapper_id,但它不起作用。它仍然试图使用purchase_offer_wrapper_id
我错在哪里?
感谢您的评分

gcuhipw9

gcuhipw91#

好了,终于找到问题了。
我必须在我的has_many关联中添加foreign_key选项。

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

相关问题