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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With