'Rails recursive association with migrations
I have a table named Nodes. Each node belongs to one father of the same table, and has one child on the same table too. This is the Node model:
class Node < ApplicationRecord
belongs_to :parent # I tried using :node instead of :parent
has_one :children # Same than above
end
How can I easily achieve this?
Solution 1:[1]
I belive what you are looking for is something like this:
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
It sets up a self-referential 1-to-many association between a node and its children.
Solution 2:[2]
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
In that case you should have parent_id
in Node
model. Also for has_one
relationship it should be child
not children
by convention.
Query will be like this: -
parent = Node.create(parent_id: nil)
child = Node.create(parent_id: parent.id)
Get all parent =>
Node.where(parent_id: nil)
Get child of a parent =>
parent.child
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |