Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails object in rescue after transaction failure is saved

i have a transaction to ensure two models get saved at the same time.

begin 
  Recipe.transaction do
    @recipe.save!
    if @dish
      @dish.save!
    end
  end
rescue

  #save failed
  flash[:notice] = "recipe.saved = #{@recipe.new_record?}"
  render 'form'
else
  #save worked
  flash[:notice] = 'Recipe added.'
  redirect_to(@recipe)
end

when validation fails for one of the models it goes to the rescue block however in the rescue block it says that the model is not a new record. i was expecting the validation to cause the transaction to fail, thus leaving the model object as a new record? what am i missing here?

like image 427
rogerfed Avatar asked Dec 02 '25 01:12

rogerfed


1 Answers

Which of the two saves is actually failing? The one for @recipe or for @dish?

Transactions are handled by your DBMS. So for example, when @dish fails to save, @recipe might've already been saved, but will be reverted by your DBMS. However, this happens behind Rails' back, and so it does not revert the state of the @recipe object.

like image 88
Stéphan Kochen Avatar answered Dec 03 '25 17:12

Stéphan Kochen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!