Note: This question was spawned from another question I had regarding the use of accepts_nested_attributes_for. You may reference that question for additional context, if needed.
I believe this question is best explained with a simple example:
class Foo < ActiveRecord::Base
has_many :bars, inverse_of: :foo
end
class Bar < ActiveRecord::Base
validates :foo_id, presence: true
belongs_to :foo, inverse_of: :bars
end
f = Foo.new()
=> #<Foo id: nil, created_at: nil, updated_at: nil>
b = f.bars.build()
=> #<Bar id: nil, foo_id: nil, created_at: nil, updated_at: nil>
f.save!
=> ActiveRecord::RecordInvalid: Validation failed: Bars foo can't be blank
Is there an easy way to fix this problem? I know that I could save f first and then build b, but my situation is a little more complex than this example (see the question I referenced above) and I’d prefer to avoid that if possible.
The child records get created at the same time as parent, this is why your validation is failing, your child is not yet persisted. to make it work i would write a custom validation like this