How can I roll back a backup transaction?

In my controller, I have code like ...

...
if user.save
    something = Something.where("thing = ?", thing)
    if !(something.nil?)
        render json: { something: something }
    else
        #I WOULD LIKE TO ROLLBACK THE user.save HERE
    end
else
    render json: { error: user.errors.full_messages }, status: :bad_request
end

I tried

raise ActiveRecord::Rollback, "Could not create new User, Something was not found."
render json: { error: "Could not create new User, Something was not found"}, status: :unprocessable_entity

instead of the ROLLBACK COMMENT area above, but this will not work. User user.save ends. He spits something on the "rails s", but he does not roll back the last transaction.

+4
source share
3 answers

You need to wrap the code in a transaction so that the rollback works correctly. Here's the documentation: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

Sort of

ActiveRecord::Base.transaction do
  # the code from your question
end

The key is that in this block there should be both a call user.save(which changes the database) and a call raise ActiveRecord::Rollback.

+3

, , -

User.transaction do
  if user.save
    something = Something.where("thing = ?", thing)
    if !(something.nil?)
      render json: { something: something }
    else
      raise ActiveRecord::Rollback
    end
  else
   render json: { error: user.errors.full_messages }, status: :bad_request
  end
end

, , .

PS:

something = Something.where("thing = ?", thing)
if !(something.nil?)

if Something.exists?(thing: thing)
+3

Instead, you can do this:

something = Something.where(thing: thing)

if something && user.save
    render json: { something: something }
else
    render json: { error: user.errors.full_messages }, status: :bad_request
end
+1
source

All Articles