保存事务失败后的rails对象

rog*_*fed 3 validation transactions ruby-on-rails

我有一个交易,以确保同时保存两个模型.

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
Run Code Online (Sandbox Code Playgroud)

当其中一个模型的验证失败时,它会进入救援区,但是在救援区中,它表示模型不是新记录.我期待验证导致事务失败,从而将模型对象留作新记录?我在这里失踪了什么?

Sté*_*hen 5

两个存储中的哪一个实际上失败了?一个适合@recipe或为@dish

事务由DBMS处理.因此,例如,当@dish无法保存时,@recipe可能已经保存,但将由您的DBMS还原.但是,这发生在Rails的后面,因此它不会还原@recipe对象的状态.