Rails活动记录关系

时间:2018-12-04 07:25:19

标签: ruby-on-rails activerecord

这是从这个问题(How can I have two columns in one table point to the same column in another with ActiveRecord?)开始的,但是细微的差别。

我有一个模型Order,该模型有三列指向同一张表Estimateestimate_idfinalized_estimate_idcost_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_estimatecost_price_estimate还是仅仅是estimate

(估价永远只会have_one个订单)

1 个答案:

答案 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表中