Read more

How to deal with 'parent id missing' error in nested forms

Deleted user #6
August 18, 2015Software engineer

tl;dr

  • Use form models to handle this problem
  • Or soften the validation to validates_presence_of :parent

Usually you would validate presence of parent object id, like in this example:

class Parent < ActiveRecord::Base
  has_many :nested, :inverse_of => :parent
  accepts_nested_attributes_for :nested
end

class Nested < ActiveRecord::Base
  belongs_to :parent
  validates_presence_of :parent_id # <- 
end
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

With the parent already persisted creating nesteds still works fine.

But one will encounter a 'parent id missing' error on creating a parent record and a nested record at once.

To be able to create parent and nested at once one has to soften the validation to only validate on the associated object:

class Nested < ActiveRecord::Base
  belongs_to :parent
  validates_presence_of :parent # <- without `_id`
end

Drawback

With this softened validation now it's technically possible to create nested records without a parent id.

To make sure developers are made aware of doing somthing undesired the database could be set to throw an error on parent id columns with null values.

An odd side effect might occur in combination with scoped uniqueness validations.

Form models for more control

Using form models and so having custom control over the creation sequence it's possible to keep the validation on parent id and still be able to create parent and nested at once.

Posted to makandra dev (2015-08-18 08:53)