Self Join database Migration in Rails

In 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:references

Then rake db:migrate You will get Employee model like
class Employee < ActiveRecord::Base
  belongs_to :manager attr_accessible :name
change to attr_accessible :name, :manager_id
then in _form.html.erb, file,
change to
<%= f.label :manager %><br /> <%= f.text_field :manager_id %>
You will get an error when you check with browser,
NameError: uninitialized constant Employee::Manager
Now change to

belongs_to :manager, class_name: "Employee"

Now if you check like,

you will get it achieved.
If you want to get


simply put

has_many :subordinates, class_name: "Employee"

If you test with browser,
You will get error, like,
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: employees.employee_id: SELECT "employees".* FROM "employees"  WHERE "employees"."employee_id" = 1
This means, it is automatically search employee_id column in employee table.
But employee_id is not available, and you are going to relate subordinates with managers,
So simply change to

has_many :subordinates, class_name: "Employee", foreign_key: "manager_id"

wow, You now got it achieved successfully. Have an enjoy. Have a nice day, with rails.