Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 839
max Avatar asked Oct 31 '13 15:10

max


2 Answers

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
like image 149
JeskTop Avatar answered Sep 18 '22 12:09

JeskTop


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
like image 39
go2null Avatar answered Sep 19 '22 12:09

go2null