我有一个名为Nodes的表。每个节点属于同一表的一个父节点,并且在同一表上也有一个子节点。这是节点模型:
class Node < ApplicationRecord
belongs_to :parent # I tried using :node instead of :parent
has_one :children # Same than above
end
我怎样才能轻松做到这一点?
我相信你想要的是这样的东西:
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
class Node < ApplicationRecord
belongs_to :parent, class_name: 'Node', optional: true
has_many :children, class_name: 'Node', foreign_key: 'parent_id'
end
它在节点及其子节点之间建立了一个自引用的一对多关联。
自参照关联
class Node < ApplicationRecord
belongs_to :parent , :class_name => "Node", :foreign_key => "parent_id", optional: true
has_one :child, :class_name => "Node", :foreign_key => "parent_id"
end
在这种情况下,Node
模型中应该有parent_id
。同样,对于has_one
关系,按照惯例,它应该是child
而不是children
。
查询如下:-
parent = Node.create(parent_id: nil)
child = Node.create(parent_id: parent.id)
获取所有父项=>
Node.where(parent_id: nil)
获取父项的子项=>
parent.child