14

模型场景:

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

模型/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   

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

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

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

4

4 回答 4

13

您已经完成了您需要做的所有事情。您可以在此页面中找到更多信息: 在此处输入图像描述

资料来源: 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
于 2013-10-31T16:44:48.640 回答
12

根据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
于 2015-06-09T15:13:36.527 回答
1

迁移中不需要任何额外的东西。parent_id 用于定义两个方向的关系。具体来说:

  1. parent - id 对应于当前节点的 parent_id 属性值的节点。

  2. children - 所有具有与当前节点的 id 属性值相对应的 parent_id 值的节点。

于 2013-10-31T16:06:47.680 回答
1

您已经使用 AddNodeToNodes 和父 ID 编写了迁移。

这在数据库级别定义它。

在'rails'级别(ActiveRecord),您在模型定义中定义has_many,即定义Node 类的Node.rb 文件。
没有“迁移”来添加 has_many。迁移用于数据库字段(和索引等),例如parent_id但不用于 Rails 样式的关系定义,例如has_many.

于 2013-10-31T17:01:01.727 回答