John Small
John Small

Reputation: 981

accepts_nested_attributes_for in recent Rails

I have a a Rails 4.1.1 project with;-

MyModel
has_many :sub_models,inverse_of: my_model
accepts_nested_attributes_for :sub_models
end

MySubModel
belongs_to: my_model,inverse_of: :sub_models
validates :my_model_id,presence: true
end 

I'm using accepts_nested_attributes to create a parent object and child objects all in the one call. It's working brilliantly. So brilliantly I don't have to think about it, it just works.

Now I've started a Rails 4.1.8 project and similar code isn't working at all. It seems that in

def create
@myModel = MyModel.new(model_params)
@myModel.save
etc

the child objects are being saved before the parent and therefore it blows up because the parent key hasn't been assigned.

Has something changed in Rails internals between 4.1.1 and 4.1.8 so that building a child object in a has_many relationship will happen before the master has been saved?

Upvotes: 0

Views: 53

Answers (1)

cjav_dev
cjav_dev

Reputation: 3105

validate presence of my_model rather than my_model id. if the object is there it should pass validation. Then it doesn't matter if the parent or child is saved first.

Upvotes: 1

Related Questions