Ric*_*ana 3 ruby-on-rails rails-migrations
我有一个名为 Nodes 的表。每个节点属于同一张表的一个父亲,并且在同一张表上也有一个孩子。这是节点模型:
class Node < ApplicationRecord
belongs_to :parent # I tried using :node instead of :parent
has_one :children # Same than above
end
Run Code Online (Sandbox Code Playgroud)
我怎样才能轻松实现这一目标?
我相信您正在寻找的是这样的:
class CreateNodes < ActiveRecord::Migration[5.0]
def change
create_table :nodes do |t|
t.belongs_to :parent,
foreign_key: { to_table: :nodes },
null: true
t.timestamps
end
end
end
Run Code Online (Sandbox Code Playgroud)
class Node < ApplicationRecord
belongs_to :parent, class_name: 'Node', optional: true
has_many :children, class_name: 'Node', foreign_key: 'parent_id'
end
Run Code Online (Sandbox Code Playgroud)
它在节点及其子节点之间建立自引用的一对多关联。