kempchee
kempchee

Reputation: 470

Simultaneous Validation of Multiple Model Updates in Rails

In rails you can use accepts_nested_attributes_for to create multiple models simultaneously in a parent child relationship. However suppose you have that same relationship, but you want to update a field on both models simultaneously, where if one model fails validation, you can be sure that the other model will not save as well. How could this be done?

def edit_multiple
  @first=First.update(first_params)
  @second=Second.update(second_params)
end

If @first passes validations but @second does not, then we will have a situation that I don't want: one model is updating but the other is not.

Upvotes: 0

Views: 406

Answers (2)

bbozo
bbozo

Reputation: 7311

First check if all model instances are @model.valid? then do a save without validation @model.save(validate: false)

Putting a transaction as boulder suggested is still a good idea in case an unexpected exception occurs

Upvotes: 0

boulder
boulder

Reputation: 3266

That was transactions are for:

First.transaction do
  @first=First.update(first_params)
  @second=Second.update(second_params)
end

Now both of them succeed or fail together. More info at ActiveRecord transactions

Upvotes: 1

Related Questions