ruby-on-rails 如何在Rails 5.2中通过STI定义父对象时指定父子关系中的实际外键?

n9vozmp4  于 4个月前  发布在  Ruby
关注(0)|答案(1)|浏览(48)

我在应用程序中使用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

字符串
一切都如预期的那样工作,直到我从show视图发出一个查询,如@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上下文。
有没有办法说得更具体一点?

yptwkmov

yptwkmov1#

您必须在has_many关联上指定foreign_key

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

相关问题