Should I use foreign_key in both has_many and belongs_to?

Asked

Viewed 110 times

1

I have two models. Office and Employee. Employee has office_id as foreign key. So, which 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 the correct one, because for me, it makes no sense to declare the foreign_key in the has_many. A co-worker disagrees, and believes that the first example is the correct one, and the foreign key must be stated on both sides of the relationship. I haven’t found many references to this subject. So, can anyone tell me which of the two is correct and why?

1 answer

1


The second 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 foreign_key in your Employee class, because by default it uses the association name 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. So a class that defines a belongs_to :person Association will use "person_id" as the default :foreign_key.

belongs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.