Isnor Creative
Isnor Creative Blog
Ruby, Ruby on Rails, Ember, Elm, Phoenix, Elixir, React, Vue

Apr 22, 2013

Nested attributes validation fails on create new record because parent id has not yet been set

The problem:

class Item < ActiveRecord::Base
    has_many :related_items
  accepts_nested_attributes_for :related_items
end

class RelatedItem
  validates :order, presence: true
end

This works fine if you’re updating an existing item, but when creating a new item, the related item order validation will fail because the item has not been saved yet, and thus has no assigned id.

Using :inverse_of will solve this problem:

class Item < ActiveRecord::Base
  has_many :related_items, inverse_of: :item
  accepts_nested_attributes_for :related_items
end

I am available for Ruby on Rails consulting work – get in touch to learn more.

Gordon B. Isnor

Gordon B. Isnor writes about Ruby on Rails, Ember.js, Elm, Elixir, Phoenix, React, Vue and the web.
If you enjoyed this article, you may be interested in the occasional newsletter.

I am now available for project work. I have availability to build greenfield sites and applications, to maintain and update/upgrade existing applications, team augmentation. I offer website/web application assessment packages that can help with SEO/security/performance/accessibility and best practices. Let’s talk

comments powered by Disqus