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

查看:20
本文介绍了保存失败后 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).

推荐答案

将项目添加到集合会立即保存它(除非用户未保存).对 save 的调用创建了自己的事务,这就是回滚的事务,而不是保存项目的事务

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

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

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