我有一个事务来确保同时保存两个模型。
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
当其中一个模型的验证失败时,它会进入救援 block ,但是在救援 block 中,它表示该模型不是新记录。我期待验证导致事务失败,从而将模型对象作为新记录?我在这里错过了什么?
最佳答案
这两个保存中的哪一个实际上失败了? @recipe
或 @dish
的那个?
事务由您的 DBMS 处理。例如,当 @dish
保存失败时,@recipe
可能已经保存,但会被您的 DBMS 恢复。然而,这发生在 Rails 背后,因此它不会恢复 @recipe
对象的状态。
关于ruby-on-rails - 保存事务失败后救援中的rails对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2305126/