Forum: Ruby on Rails ActiveRecord callback chain exception?

Posted by Craayzie As a fox (craayzie)
on 2013-02-20 03:51
I'm creating an ActiveRecord object A and want to update object B during
the process even if the creation of object A is rolled back due to a
before_create callback returning false.

Is there a way for me to do this?

It seems that once you're in the ActiveRecord callback chain your DB
updates will be rolled back unless the entire callback chain returns
true.

Another way to look at this: I need to track all ActiveRecord "create"
attempts but it seems that I'm unable to use callbacks or observers to
do this since both are referenced within the ActiveRecord callback
chain.

How would you go about doing this?

Thanks for the help!
Posted by Frederick Cheung (Guest)
on 2013-02-20 09:52
(Received via mailing list)
On Wednesday, February 20, 2013 2:51:49 AM UTC, Ruby-Forum.com User 
wrote:
>
> Another way to look at this: I need to track all ActiveRecord "create"
> attempts but it seems that I'm unable to use callbacks or observers to
> do this since both are referenced within the ActiveRecord callback
> chain.
>
> How would you go about doing this?
>

I wouldn't claim that this is a good idea (and I expect it would violate
most peoples expectations about all aspects of the save rolling back if 
a
callback returns false but...

Database connections and hence transactions happen on a per thread 
basis,
therefore if you create a separate thread and create B it is created 
using
a separate database connection and won't be affected by the rollback of 
the
main save. This could be quite simple:

Thread.new do
    B.create
end.join

Will run that second thread and wait until it exits before continuing.
Watch out for cross thread exception handling and make sure that 
B.create
isn't going to do anything thread dangerous.

Fred
Posted by Craayzie As a fox (craayzie)
on 2013-02-21 03:18
That's pretty clever :)

Thanks Fred!
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.