Using transaction the right way


#1

I wonder if my transaction is well written ?
I create the user record first , then the issue record (no validation)
if the user record is valid and saved
if anything happen when saving the issue, I want to rollback the user
record…

def infos_send
@franchise = Franchise.scoped_by_mother_of_all(true).first
@user = ProspectUser.new(params[:user])

User.transaction do
  if @user.save
    create_info_request_issue  #private method
    @issue.save
    raise ActiveRecord::Rollback
    flash[:notice] = I18n.t(:notice_successful)
    redirect_back_or_default  :action => 'index'
  else
    render  :action => 'infos'
  end
end

end

thanks for you help

erwin


#2

On 21 Mar 2009, at 11:15, Kad K. wrote:

I wonder if my transaction is well written ?
I create the user record first , then the issue record (no validation)
if the user record is valid and saved
if anything happen when saving the issue, I want to rollback the user
record…

It looks a bit odd - you always raise ActiveRecord::Rollback, no
matter what happened.
In case you did’t know, if an exception is raised inside the
tranasaction block then a rollback will happen for you automatically.

Fred


#3

Frederick C. wrote:

On 21 Mar 2009, at 11:15, Kad K. wrote:

I wonder if my transaction is well written ?
I create the user record first , then the issue record (no validation)
if the user record is valid and saved
if anything happen when saving the issue, I want to rollback the user
record…

It looks a bit odd - you always raise ActiveRecord::Rollback, no
matter what happened.
In case you did’t know, if an exception is raised inside the
tranasaction block then a rollback will happen for you automatically.

Fred

Yes sorry… this line should have been deleted…
is the remaining code OK ?

thanks