这是从这个问题(How can I have two columns in one table point to the same column in another with ActiveRecord?)开始的,但是细微的差别。
我有一个模型Order
,该模型有三列指向同一张表Estimate
:estimate_id
,finalized_estimate_id
,cost_price_estimate_id
。
class Order < ApplicationRecord
belongs_to :estimate
belongs_to :finalized_estimate, class_name: "Estimate", optional: true
belongs_to :cost_price_estimate, class_name: "Estimate", optional: true
end
估计类是什么样的?其次,估算值可以知道它来自哪一列吗?即估计模型是否/可以知道它是finalized_estimate
,cost_price_estimate
还是仅仅是estimate
?
(估价永远只会have_one
个订单)
答案 0 :(得分:2)
只需执行以下操作
class Order < ApplicationRecord
belongs_to :estimate # default foreign_key is estimate_id
belongs_to :finalized_estimate, class_name: "Estimate", foreign_key: 'finalized_estimate_id', optional: true
belongs_to :cost_price_estimate, class_name: "Estimate", foreign_key: 'cost_price_estimate_id', optional: true
end
休息很好。 :)
说明:
与配置(COC)相比,铁路更喜欢惯例,即
编写finalized_estimate
时,它会按照惯例寻找FinalizedEstimate
模型而不是Estimate
并搜索finalized_estimate_id
,因此必须明确提供它。
对于belongs_to :estimate
,它隐式获取类Estimate
和Foreign_key estimate_id
。
在另一面,
class Estimate < ApplicationRecord
has_many :orders
has_many :finalized_order, class_name: "Order", foreign_key: 'finalized_estimate_id'
has_many :cost_price_order, class_name: "Order", foreign_key: 'cost_price_estimate_id'
end
这里的主键始终以orders
的形式出现在id
表中