Is there a way to use the transaction method in a controller class?
In a controller method, I would like to save the user model objects
and several other model objects in the database in a transaction:
either save all or none. This can be done in the model class but
ActiveRecord::Base.transaction as the full name indicates is is not
available in ApplicationController . Is there a way to call the
transaction method in a controller class? Thanks much.
ActiveRecord::Base.transaction as the full name indicates is is not
available in ApplicationController .
Did not get the above statement…Anyway you can do like
def controller_action
begin
ActiveRecord::Base.transaction do
---------your all transactions here
end
rescue ActiveRecord::ActiveRecordError => e:
---------- rescue code here
else
----------in case nothing raised
end
end
But better to move this to model so to make controller skinny
Sijo
Thanks, Sijo. That works.
I would like to move this logic down to the model level but I can’t
because the transaction involves different models. Any suggestions?
Thanks.
Learn by Doing wrote:
Thanks, Sijo. That works.
I would like to move this logic down to the model level but I can’t
because the transaction involves different models. Any suggestions?
Thanks.
Create a non-AR model to handle the transaction dispatch. Sijo is quite
right that this does not belong in the controller.
Best,
Marnen Laibow-Koser
http://www.marnen.org
[email protected]
Learn by Doing wrote:
Thanks Marnen! What do you mean by a non-AR model?
I mean a model class that does not inherit from ActiveRecord.
I have users and
each
user has a spec. I’d like to do something like thistransaction do
user.save!
spec.save!
end
Right. Put that in a method of your new class, then call it from the
controller.
Thanks.
Best,
Marnen Laibow-Koser
http://www.marnen.org
[email protected]
I see. Thanks, Marnen!
On Fri, Jul 17, 2009 at 12:04 PM, Marnen Laibow-Koser <
Thanks Marnen! What do you mean by a non-AR model? I have users and
each
user has a spec. I’d like to do something like this
transaction do
user.save!
spec.save!
end
Thanks.
On Fri, Jul 17, 2009 at 11:53 AM, Marnen Laibow-Koser <