Home > database >  How do you associate objects to objects of the same type in Rails
How do you associate objects to objects of the same type in Rails

Time:10-31

I have a model of Blocks in a table (also blocks).

I want to make it so each Block can be associated to one or many other blocks as both parent and children.

So each Block could need (?) both 'belongs_to' and 'has_many' other blocks.

I tried creating a migration like this

class AddChildrenToBlocks < ActiveRecord::Migration[7.0]
  def change
    add_reference :blocks, :children
  end
end

That successfully added a column for "ID's" in my blocks table but I have a feeling that doesn't 'know' it's an object, it's just adding an ID column as it would for 'anything'.

Is it possible to create a reference/association in Rails where an instance of an Object can have many (or no) children/parents of other Objects of the same type?

A simple example might be :

Block 1 : Parent (Block 3, 2) Children (Block 4, 5, 6)

Block 2 : Parent (Block 7) Children (Block 10, 11, 12)

CodePudding user response:

Each block can have a parent.

add_reference :blocks, :parent

For each parent you can find all its children

belongs_to :parent, class_name: 'Block', foreign_key: :parent_id, optional: true
has_many :children, class_name: 'Block', foreign_key: :parent_id
  • Related