Should I use foreign_key in both has_many and belongs_to?

1

I have two models. Office and Employee. Employee has office_id as foreign key. So which one is correct?

class Office < ActiveRecord::Base
  has_many :employees, foreign_key: 'office_id' 
end

class Employee < ActiveRecord::Base
  belongs_to :office, foreign_key: 'office_id'
end

Or

class Office < ActiveRecord::Base
  has_many :employees
end

class Employee < ActiveRecord::Base
  belongs_to :office, foreign_key: 'office_id'
end

I think the second example is correct, because for me, it does not make sense to declare foreign_key in has_many . A co-worker disagrees, and believes that the first example is correct, with the foreign key being declared on both sides of the relationship. I have not found many references to this subject. So, can anyone tell me which one is correct and why?

    
asked by anonymous 04.03.2016 / 19:53

1 answer

1

The 2nd option is the correct one, as you said yourself is your Employee class that has the foreign key in the relation. You can also omit the placement of the foreign_key in your Employee class, because by default it uses the name of the association followed by the _id suffix.

According to the documentation:

  

: foreign_key Specify the foreign key used for the association. By   default this is guessed to be the name of the association with an   "_Id" suffix. It's a class that defines a belongs_to: person association   will use "person_id" as the default: foreign_key.

belongs

    
04.03.2016 / 23:05