14

モデル シナリオ:

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           

デシベル/移行/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

1

AddNodeToNodes と親 ID を使用して移行を既に作成しています。

それはデータベースレベルでそれを定義します。

「rails」レベル (ActiveRecord) では、モデル定義、つまり Node クラスを定義する Node.rb ファイルで has_many を定義します。
has_many を追加する「移行」はありません。移行は、 などのデータベース フィールド (およびインデックスなど) に使用されますが、 などparent_idの Rails スタイルの関係定義には使用されませんhas_many

于 2013-10-31T17:01:01.727 に答える