我在应用程序中使用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上下文。
有没有办法说得更具体一点?
1条答案
按热度按时间yptwkmov1#
您必须在
has_many
关联上指定foreign_key
:字符串
否则,Rails假设DataProcess模型的外键是Treatment上的
data_process_id
列。参考网址:https://guides.rubyonrails.org/association_basics.html#options-for-has-many-foreign-key