I trying transactions for the first time and trying to figure out the
best (DRY?) way to get the error message outside the transaction block.
If in a controller if I have
def create
Memo.transaction do @memo = Memo.new(params[:memo]) # polymorphic build @resource = @memo.memoble # get parent @resource.create_memo(@memo) # saves memo and updates parent fields
end
… #how do I check if there was a rollback so I can redirect based on
pass fail?
end
In the parents model I have
def create_memo #does stuff and if there is an error not in validations
…
raise ActiveRecord::Rollback, ‘Memo was NOT created. Payment exceeds
balance due’
…
end
I had create_memo return nil or error message and raised the exception
in the controller, but that does not seem to be the best way - but it
works.
The basic question is “How do I tell if a transaction was committed or
rolled back?”
def create_memo #does stuff and if there is an error not in validations
…
raise ActiveRecord::Rollback, ‘Memo was NOT created. Payment exceeds
balance due’
…
end
Steve
I am guessing that you are planning on using later on the message that
you are raising. Why not just add the error to your memo object errors
and then check in your controller if your memo.errors is empty or not?
I am guessing that you are planning on using later on the message that
you are raising. Why not just add the error to your memo object errors
and then check in your controller if your memo.errors is empty or not?
pepe
Thanks for both suggestion. Again, first time I’ve tried transactions
and there is a lot of “I didn’t know you could do that!”.
I tried
raise ActiveRecord::Rollback, 'Memo was NOT created. Payment exceeds
because that was the example in the rdoc. I did read that if would just
eat the exception.
Never did my own exception, but will sure to go that path.
Didn’t know you could add errors to the object. I know now more than I
did yesterday.
I had create_memo return nil or error message and raised the exception
in the controller, but that does not seem to be the best way - but it
works.
The basic question is “How do I tell if a transaction was committed or
rolled back?”
If I were you I wouldn’t raise ActiveRecord::Rollback (which
transaction swallows silently). I’d raise my own exception class, it
will still cause the transaction to be rolled back but the exception
will continue upwards and you can then rescue it in your controller,
outside the transaction block and take whatever action is appropriate
to the app
Fred
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.