transaction in controller

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.

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.

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 this

transaction do   user.save!   spec.save! end

Right. Put that in a method of your new class, then call it from the controller.

Thanks.

Best,

I see. Thanks, Marnen!