I feel the following self join model example given on http://guides.rubyonrails.org/association_basics.html#self-joins is incorrect.
class Employee < ActiveRecord::Base
has_many :subordinates, :class_name => "Employee",
:foreign_key => "manager_id"
belongs_to :manager, :class_name => "Employee"
end
I feel it should be as following. Can you please suggest which one is correct and why?
class Employee < ActiveRecord::Base
has_many :subordinates, :class_name => "Employee",
belongs_to :manager, :class_name => "Employee", :foreign_key => "manager_id"
end
My rationale: The model bearing belongs_to relation carries the foreign_key for the model it references to.
The example is correct.
The “convention over configuration” mantra applies here, you only need to specify what the foreign key if it is not
"#{name_of_association}_id"Therefore
belongs_to :manager, :class_name => "Employee"implies the foreign key ismanager_idHowever
has_many :subordinates, :class_name => "Employee"assumessubordinates_idto be the childrens’ foreign key, which is why if must be defined. The definition of:foreign_keyin a has_many will be for the child and will join against the current model’sid.