Wow I’ve been struggling with this for whole day, following the “official” ruby on rails guides document, and just discovered that I might have been misguided by the document all along. I just want to confirm if this is true.
If you go to http://guides.rubyonrails.org/association_basics.html and under 2.10. self joins section it says:
class Employee < ActiveRecord::Base
has_many :subordinates, :class_name => "Employee"
belongs_to :manager, :class_name => "Employee",
:foreign_key => "manager_id"
end
Now, I’m a newbie and just believed in this code (What else can I do?) and wrote some code that’s a variation of this self join case. However the more I looked at it the more it didn’t feel right. isn’t :subordinates supposed to have the :foreign_key field instead of :manager? Anyway I’ve just changed it so that the code is something like:
class Employee < ActiveRecord::Base
has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id"
belongs_to :manager, :class_name => "Employee"
end
and now it’s working. Am I missing something? Or is the official document wrong? It’s hard to believe that the official document would present incorrect information but maybe that’s the way it is.
That’s right, the guide document is incorrect at the time of this writing.
The
belongs_todoesn’t need the:foreign_keyoption because AR will infermanager_idfrom the name of the association (“manager”). As documented, AR would raise an error when, given an Employee@dwightone attempts to@dwight.subordinates, because AR would useemployee_idin the WHERE condition of the SELECT statement.According to the AR documentation passing the
:foreign_keyoption tohas_manyresults in declaring the FK that will be used when generating the query for@dwight.subordinates.