Search code examples
validationruby-on-rails-4simple-formnested-attributes

nested form objects fails validation complaining of missing parent_id


I use simple_form. When using rails accepts_nested_attributes_for, the form fails validation complaining that the nested attributes validation failed because the id of the parent object can't be blank (validates_presence_of).

I know the parent object id is being submitted, because if I remove validation the form submits, and the child record is valid. So, the validations are looking at the params before the parent id is associated with the child...and therefor failing. This seems strange. Why is rails running validation at a stage in form submission before the parent of the nested attributes is correctly associated?

Is there a rails way for handling this scenario?


Solution

  • Just found the answer to this in the Rails docs. Here's their example, using inverse_of:

    class Member < ActiveRecord::Base
      has_many :posts, inverse_of: :member
      accepts_nested_attributes_for :posts
    end
    
    class Post < ActiveRecord::Base
      belongs_to :member, inverse_of: :posts
      validates_presence_of :member
    end