Ask A Question


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"

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: { |f|
  f.parent   = f


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

I've also tried { |f|
  f.parent_id = = Files.next_sequence_value

And I have looked at build_parent

Join the discussion
Create an account Log in

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

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

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

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

    © 2023 GoRails, LLC. All rights reserved.