Self Join database Migration in RailsIn designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:
rails g scaffold Employee name:string manager:referencesThen rake db:migrate You will get Employee model like
Employee < ActiveRecord::Base
belongs_to :manager attr_accessible :name
attr_accessible :name, :manager_id
then in _form.html.erb, file,
<%= f.label :manager %><br /> <%= f.text_field :manager_id %>
You will get an error when you check with browser,
Now change to
belongs_to :manager, class_name: "Employee"
Now if you check like,
you will get it achieved.
If you want to get
has_many :subordinates, class_name: "Employee"
If you test with browser,
You will get error, like,
This means, it is automatically search employee_id column in employee table.
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: employees.employee_id: SELECT "employees".* FROM "employees" WHERE "employees"."employee_id" = 1
But employee_id is not available, and you are going to relate subordinates with managers,
So simply change to