views:

90

answers:

2

I need to create a row in both tickets and users table... I just need to know how to process in case the transaction fails.

@ticket.transaction do
 @ticket.save!
 @user.save!
end
 #if (transaction succeeded)
  #.....
 #else (transaction failed)
  #......
 #end

On a side note I'd just like to thank everyone who participates at stack overflow for helping a designer learn more programming... I appreciate the time you guys take out of your day to answer n00b questions like this :)

A: 

i'm also a beginner, but i believe that you can check @ticket.errors and @user.errors and validate according to their responses

also the save method should return a boolean that determines if the save was successful

mportiz08
+4  A: 

If you are using the save! method with a bang (exclamation point), the application will throw an exception when the save fails. You would then have to catch the exception to handle the failure. You can use the save method without a bang, and that will return a value of false when it fails to save.

So you can do something like this:

@ticket.transaction do
        success = @ticket.save
        success = @user.save && success
end
if success
   #yea
else
   #fail
end

There are simpler ways to express this, but this should give you the idea of what's going on.

To go the exception handling route do:

begin
  @ticket.transaction do
    @ticket.save!
    @user.save!
  end
  #handle success here
rescue ActiveRecord::RecordInvalid => invalid
   #handle failure here
end
MattMcKnight
Thanks so much Matt, I appreciate it :)
Kevin