1

This follows from this question (How can I have two columns in one table point to the same column in another with ActiveRecord?) but there is a slightly different nuance.

I have a model Order, which has three columns that point to the same table 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

What would the estimate class look like? And secondly could an estimate know which column it is from? I.e. will/can an estimate model know it is a finalized_estimate, cost_price_estimate or just an estimate?

(Estimate will always only have_one order)

Toma
  • 239
  • 3
  • 11

1 Answers1

2

Just do following,

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

Rest is fine. :)

Explaination:

Rails prefer convention over configuration(COC) i.e.

When you write finalized_estimate, It looks for FinalizedEstimate model instead of Estimate by convention and search for finalized_estimate_id, So you have to provide it explicitly.

For belongs_to :estimate, It gets class Estimate & foreign_key estimate_id implicitly.

In other side,

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

Here primary key is always present at orders table as id

ray
  • 5,454
  • 1
  • 18
  • 40
  • Thanks ray, My understanding is that the default foreign key is set according to the name. So `:finalized_estimate` will become `finalized_estimate_id `. Not sure if this changes anything in the class. My main concern though is when you have an estimate object, how it would know which "type" of estimate it is.. – Toma Dec 04 '18 at 09:14
  • @Toma, I added explanation which will clear your idea. Upvote & accept answers if it is satisfactory :) – ray Dec 04 '18 at 10:59
  • `When you write finalized_estimate, It looks for FinalizedEstimate model instead of Estimate by convention and search for finalized_estimate_id, So you have to provide it explicitly.` => this is solved by the piece of code `class_name: "Estimate"` which was there originally can you expand the explanation in the other direction, I want know if `Estimate.order` can work – Toma Dec 05 '18 at 07:40
  • @Toma It will be same case for has_one also. – ray Dec 05 '18 at 13:58