18

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.

Baldrick
  • 23,882
  • 6
  • 74
  • 79
Vlad
  • 8,038
  • 14
  • 60
  • 92
  • 2
    Yes, you're right. An association named `manager` would of course correctly assume the foreign key `manager_id`. And then the `subordinates` association would the same way assume the invalid foreign_key `subordinate_id` so that is the one that needs changing. – DanneManne Mar 23 '12 at 07:50
  • 6
    I send commit to docrails, that fixes this error – mikdiet Mar 23 '12 at 10:35
  • I see how the :foreign_key=>'manager_id' was correctly placed.As far as I know the foreign_key goes with the belongs_to side of the relation.I would like to see an example of what you call "...and now it's working".Of course I could be missing something. – Daniel Mar 31 '12 at 17:23

1 Answers1

1

That's right, the guide document is incorrect at the time of this writing.

The belongs_to doesn't need the :foreign_key option because AR will infer manager_id from the name of the association ("manager"). As documented, AR would raise an error when, given an Employee @dwight one attempts to @dwight.subordinates, because AR would use employee_id in the WHERE condition of the SELECT statement.

According to the AR documentation passing the :foreign_key option to has_many results in declaring the FK that will be used when generating the query for @dwight.subordinates.

ybakos
  • 8,152
  • 7
  • 46
  • 74