Rails: 如何回滚 with_lock 块内的活动记录?
Rails: How to rollback active record inside a with_lock block?
我想在条件匹配时回滚 with_lock
内的事务。我尝试了 raise ActiveRecord::Rollback
但它不起作用并且仍然创建记录。这是我的代码的简短版本。
object.with_lock do
a = num
for i in [1..10] do
unless obj1.tickets.create(params)
raise ActiveRecord::Rollback
end
a += 1
end
unless obj2.update_attributes(a: a) ## I tried 'if' in place of 'unless' for test
raise ActiveRecord::Rollback
end
end
EDIT1
这对我有用
object.with_lock do
ActiveRecord::Base.transaction(requires_new: true) do
a = num
for i in [1..10] do
unless obj1.tickets.create(params)
raise ActiveRecord::Rollback
end
a += 1
end
unless obj2.update_attributes(a: a)
raise ActiveRecord::Rollback
end
end
end
Raising rollback works inside a transaction like this.
ApplicationRecord.transaction
# ...
unless obj1.tickets.create(params)
raise ActiveRecord::Rollback, "Call tech support!"
end
end
我想在条件匹配时回滚 with_lock
内的事务。我尝试了 raise ActiveRecord::Rollback
但它不起作用并且仍然创建记录。这是我的代码的简短版本。
object.with_lock do
a = num
for i in [1..10] do
unless obj1.tickets.create(params)
raise ActiveRecord::Rollback
end
a += 1
end
unless obj2.update_attributes(a: a) ## I tried 'if' in place of 'unless' for test
raise ActiveRecord::Rollback
end
end
EDIT1
这对我有用
object.with_lock do
ActiveRecord::Base.transaction(requires_new: true) do
a = num
for i in [1..10] do
unless obj1.tickets.create(params)
raise ActiveRecord::Rollback
end
a += 1
end
unless obj2.update_attributes(a: a)
raise ActiveRecord::Rollback
end
end
end
Raising rollback works inside a transaction like this.
ApplicationRecord.transaction
# ...
unless obj1.tickets.create(params)
raise ActiveRecord::Rollback, "Call tech support!"
end
end