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?
You've done everything you needed to do.You can find the more informations in this page:

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
Per RailsGuides, this is an example of a Self-Join.
# model
class Node < ActiveRecord::Base
  has_many :children, class_name: "Node", foreign_key: "parent_id"
  belongs_to :parent, class_name: "Node"
end
# migration
class CreateNodes < ActiveRecord::Migration
  def change
    create_table :nodes do |t|
      t.references :parent, index: true
      t.timestamps null: false
    end
  end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With