在save()失败后,Rails不会回滚事务 [英] Rails not rolling back transaction after failed save()

查看:89
本文介绍了在save()失败后,Rails不会回滚事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个域模型:用户有一组项目,并且项目的状态可能无法通过验证。

I have this domain model: A user has group of items, and the state of the items can fail a validation.

验证工作正常,我什至看到当我使用 save!时会调用异常。

Validation works fine, and I even see exceptions get called when I use save!.

在我的控制器中,我有这个:

In my controller, I have this:

@user.items() << item

if @user.save
  render :json => {}, :status => :ok
else
  render :json => {:status => :error, :errors => item.errors}, :status => :bad_request
end

第一个POST成功,第二个POST失败,但是当我命中索引后,我仍然看到两个对象,好像第二个事务从未回滚。

The first POST succeeds, and the second POST fails, but when I hit the index, I still see two objects, as if the second transaction never rolled back. What is going on?

我的测试是这样的:

  post :create
  post :create
  get :index
  ActiveSupport::JSON.decode(response.body).length.should == 1

编辑:即使在运行服务器时,事务也不会回滚(sqlite3)。

Even when running a server, transactions are not being rolled back (sqlite3).

推荐答案

向集合中添加项目会立即将其保存(除非用户未保存)。
保存调用将创建自己的事务,即回滚,而不是保存项目的事务。

Adding an item to the collection saves it immediately (unless the user is unsaved). The call to save creates its own transaction and that is what is rolled back, not the transaction in which the item is saved

您可以将所有内容强制放入通过显式创建一个交易。

You could force everything into the same transaction by creating one explicitly.

begin
  User.transaction do
    @user.items << item
    @user.save!
    render :json => {}, :status => :ok
  end
rescue ActiveRecord::RecordInvalid
  render :json => {:status => :error, :errors => item.errors}, :status => :bad_request
end

这篇关于在save()失败后,Rails不会回滚事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆