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

Posted . Visible to the public.

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

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.

Martin Straub
Last edit
Martin Straub
License
Source code in this card is licensed under the MIT License.
Posted by Martin Straub to makandra dev (2015-08-18 06:53)