Home > Enterprise >  Self Referencing problem in Rails active record
Self Referencing problem in Rails active record

Time:12-08

I have a rails model called Task. And I use self-referencing design with my model

class Task < ApplicationRecord

  belongs_to :parent, class_name: "Task"
  has_many :children, class_name: "Task",foreign_key: "parent_id"
end

So when I create my first object, It keep saying that "Parent must exist". I'm not sure how to make a object as a root in this hierarchy . Please help me with this

CodePudding user response:

Change from belongs_to :parent, class_name: "Task" to belongs_to :parent, optional: true, class_name: "Task".

With that, you will be able to create a task without a parent. To validate if a task is a child or not you can check if parent_id has any value:

def child?
  parent_id.present?
end

Reference: https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

  • Related