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.