如何为属于自身的rails模型编写迁移

max*_*max 11 ruby ruby-on-rails ruby-on-rails-4

模型场景:

A node can belong to a parent node and can have child nodes.
Run Code Online (Sandbox Code Playgroud)

车型/ node.rb

class Node < ActiveRecord::Base                                                                

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

end           
Run Code Online (Sandbox Code Playgroud)

分贝/迁移/ 20131031144907_create_nodes.rb

class CreateNodes < ActiveRecord::Migration
  def change
    create_table :nodes do |t|
      t.timestamps
    end
  end
end   
Run Code Online (Sandbox Code Playgroud)

然后我想做迁移添加关系:

class AddNodesToNodes < ActiveRecord::Migration
  def change
    add_column :nodes, :parent_id, :integer
    # how do i add childen?
  end
end
Run Code Online (Sandbox Code Playgroud)

如何在迁移中添加has_many关系?

Jes*_*Top 11

您已经完成了所需的一切.您可以在此页面中找到更多信息: 在此输入图像描述

资料来源:http://guides.rubyonrails.org/association_basics.html

node.parent将找到parent_id节点id并返回父节点.

node.children会发现parent_id是节点id并返回子节点.

当你添加关系时,你可以在Rails 4中这样做:

## rails g migration AddNodesToNodes parent:belongs_to

class AddNodesToNodes < ActiveRecord::Migration
  def change
    add_reference :nodes, :parent, index: true
  end
end
Run Code Online (Sandbox Code Playgroud)


go2*_*ull 10

Per RailsGuides,这是一个自我加入的例子.

# 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
Run Code Online (Sandbox Code Playgroud)