max max - 4 months ago 29
Ruby Question

How to write a migration for a rails model that belongs_to itself

model scenario:

A node can belong to a parent node and can have child nodes.


models/node.rb

class Node < ActiveRecord::Base

has_many :children, class_name: "Node", foreign_key: "parent_id"
belongs_to :parent, class_name: "Node"

end


db/migrations/20131031144907_create_nodes.rb

class CreateNodes < ActiveRecord::Migration
def change
create_table :nodes do |t|
t.timestamps
end
end
end


And then I want to do I migration to add the relations:

class AddNodesToNodes < ActiveRecord::Migration
def change
add_column :nodes, :parent_id, :integer
# how do i add childen?
end
end


How do i add the has_many relationship in the migratation?

Answer

You've done everything you needed to do.You can find the more informations in this page: enter image description here

Source: http://guides.rubyonrails.org/association_basics.html

node.parent will find the parent_id is the node id and return the parent.

node.children will find the parent_id is the node id and return the children.

And when you add relations, you can do like this in Rails 4:

## rails g migration AddNodesToNodes parent:belongs_to

class AddNodesToNodes < ActiveRecord::Migration
  def change
    add_reference :nodes, :parent, index: true
  end
end