Rails 5.2 中通过 STI 定义父级时,如何指定父子关系中的实际外键?

问题描述 投票:0回答:1

我在应用程序中使用 STI,因此 procedure 和 DataProcess 模型都继承自 BusinessProcess 类:

class BusinessProcess < ApplicationRecord
end

class Procedure < BusinessProcess
end

class DataProcess < BusinessProcess
  has_many :treatments, inverse_of: :parent, dependent: :destroy
end

class Treatment < ApplicationRecord
  belongs_to :parent, class_name: "DataProcess", foreign_key: "business_process_id"
end

一切都按预期工作,直到我从显示视图发出诸如

@data_process.treatments.first
之类的查询。这会引发以下错误:

*** ActiveRecord::StatementInvalid Exception: PG::UndefinedColumn: FEHLER:  Spalte treatments.data_process_id existiert nicht
LINE 1: SELECT  "treatments".* FROM "treatments" WHERE "treatments"....
                                                       ^
: SELECT  "treatments".* FROM "treatments" WHERE "treatments"."data_process_id" = $1 ORDER BY "treatments"."id" ASC LIMIT $2

看起来 Rails 没有考虑外键是 business_process_id,而是生成它自己的外键,忘记了 STI 上下文。

有没有更具体的方法?

ruby-on-rails activerecord
1个回答
0
投票

您必须在

foreign_key
关联上指定
has_many

has_many :treatments, inverse_of: :parent, dependent: :destroy, foreign_key: "business_process_id"

否则,Rails 假定 DataProcess 模型的外键是 Treatment 上的

data_process_id
列。

参考:https://guides.rubyonrails.org/association_basics.html#options-for-has-many-foreign-key

© www.soinside.com 2019 - 2024. All rights reserved.