The rails docs are apparently in error – http://guides.rubyonrails.org/association_basics.html#selfjoins)
In designing a data model, you will sometimes find a model that should
have a relation to itself. […]
class Employee < ActiveRecord::Base
has_many :subordinates, :class_name => "Employee"
belongs_to :manager, :class_name => "Employee",
:foreign_key => "manager_id"
end
With this setup, you can retrieve @employee.subordinates and
@employee.manager.
Actually, in at least the console, an error is generated in the above if foreign_key is not “employee_id”.
Here’s my specific code:
#Table name: plates
#
# id :integer not null, primary key
# name :string(255)
# datetime :datetime
# parent_id :integer
# precision :integer
# tags :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class Plate < ActiveRecord::Base
has_many :templates
has_many :children, :class_name => "Plate"
belongs_to :parent, :class_name => "Plate",
:foreign_key => "parent_id"
[...]
…and the query I run:
irb(main):002:0> Plate.find_by_name("blog090822").children.first
If I run that it generates SQL looking for plate_id and then returns an error for non-existant column. If I change the column name to plate_id through a migration, reseed the DB and rerun the query it works.
If this is a rails documentation error, how commonplace is that.
In the API documents, there are some explanations to
foreign_key. Forbelongs_to:For
has_many:So in your case, the
foreign_keyfor :children should beplate_id, and theforeign_keyfor :parent should beparent_id.To let your code work while keeping the data schema, only the
foreign_keyfor :children is necessary, which override the defaultforeign_keywithparent_id.The code in the Rails guide could be wrong.