How do you prevent database changes inside a Rails ActiveRecord before_create filter from getting rolled back when it returns false? -
I have added a filter before one of my ActiveRecord models and updating some database inside that filter I am
Sometimes I return false to the filter to avoid the construction of the target model, but which have other database changes ( While inside the filter) to get rolled back.
Update # 1 : There is some pseudo code explaining my problem:
class widget & lt; Before ActiveRecord :: Base: update_instead def update_instead if some_condition? Update_some_record_in_same_model # This rolling roll is returning false false # do not make a new record and the other right return it # Update it to end and end and end and end and Android.
Update # 2 : Some good answers were given down but each had its own drawbacks I was ending overriding the method of making such a way: < / P>
def make super till the upgrade? # Yes, I have reversed the return value from the top end
Just me It had to do recently. You must specifically request a second connection from AR. Then perform your changes on that connection. In this way, if the creation fails and withdraws the transaction, then the changes of your callback were already done in a different transaction.
Ignore my answer given above In the example code, you have actually clarified things.
class foo & lt; Before ActiveRecord :: Base: update_instead def update_instead dbconn = self.class.connection_pool.checkout dbconn.transaction do dbconn.execute ("update foos set name = 'updated'") end self.class.connection_pool.checkin (dbconn) False end end & gt; & Gt; Foo.create (: name => 'sam') = & gt; # & Lt; Foo ID: Zero, Name: "Sam", Created: Zero, Updated: Zero & gt; & Gt; & Gt; Foo.all = & gt; [# And Lieutenant; Foo ID: 2, Name: "updated", created_at: "2009-10-21 15:12:55", updated_at: "2009-10-21 15:12:55" & gt;]
Comments
Post a Comment