gpt4 book ai didi

ruby-on-rails - 如何防止 Rails ActiveRecord before_create 过滤器中的数据库更改在返回 false 时回滚?

转载 作者:行者123 更新时间:2023-12-04 03:54:04 27 4
gpt4 key购买 nike

我在我的一个 Rails ActiveRecord 模型中添加了一个 before_create 过滤器,在该过滤器中我正在做一些数据库更新。

有时我会从过滤器返回 false 以阻止创建目标模型,但是这导致了我所做的所有其他数据库更改(在过滤器内)回滚。

我怎样才能避免这种情况?

更新 #1:这是解释我的问题的一些伪代码:

class Widget < ActiveRecord::Base
before_create :update_instead

def update_instead
if some_condition?
update_some_record_in_same_model # this is getting rolled back
return false # don't create a new record
else
return true # let it continue
end
end
end

更新 #2:下面有一些很好的答案,但每个都有其缺点。我最终像这样重写了创建方法:

def create
super unless update_instead? # yes I reversed the return values from above
end

最佳答案

我最近不得不这样做。您需要专门向 AR 请求另一个连接。然后在该连接上执行您的更改。这样,如果创建失败并回滚事务,则回调的更改已经在不同的事务中提交。

忽略我上面的回答。您刚刚提供的示例代码确实阐明了一些事情。

class Foo < ActiveRecord::Base
before_create :update_instead

def update_instead
dbconn = self.class.connection_pool.checkout
dbconn.transaction do
dbconn.execute("update foos set name = 'updated'")
end
self.class.connection_pool.checkin(dbconn)
false
end
end


>> Foo.create(:name => 'sam')
=> #<Foo id: nil, name: "sam", created_at: nil, updated_at: nil>
>> Foo.all
=> [#<Foo id: 2, name: "updated", created_at: "2009-10-21 15:12:55", updated_at: "2009-10-21 15:12:55">]

关于ruby-on-rails - 如何防止 Rails ActiveRecord before_create 过滤器中的数据库更改在返回 false 时回滚?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1597434/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com