【问题标题】:How to write a migration for a rails model that belongs_to itself如何为属于自己的 Rails 模型编写迁移
【发布时间】:2013-10-31 15:47:54
【问题描述】:

模型场景:

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关系?

【问题讨论】:

  • 据我所知,您已经完成了您需要做的所有事情。你有什么错误吗?

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

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

来源: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

【讨论】:

    【解决方案2】:

    根据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
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        【解决方案4】:

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

        在数据库级别定义它。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-03
          • 2023-03-19
          • 2018-04-20
          • 1970-01-01
          • 2018-12-22
          相关资源
          最近更新 更多