All threads / How do you create and save an Active Record instance that has a reference to itself?
Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do you create and save an Active Record instance that has a reference to itself?

Perry Smith asked in Rails

Files is an Active Record model that has a reference to its parent of the same type:

class Files < ActiveRecord::Base
  belongs_to :parent, class_name: "Files"
end

I want to create a root entry whose parent is itself (which mimics the root directory which has .. that points to itself).

I have tried several various things most of which end up trying to save the record to the database with the parent still set to null. The db is set up to throw an exception if that field is null. I've tried:

Files.new { |f|
  f.parent   = f
}.save

and

Files.create { |f|
  f.parent   = f
}

I've also tried

Files.new { |f|
  f.parent_id = f.id = Files.next_sequence_value
}.save

And I have looked at build_parent

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 66,029+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2022 GoRails, LLC. All rights reserved.