# Transactional Services on RoR

**URL:** <https://www.ruby-forum.com/t/transactional-services-on-ror/128014>\
**Category:** Rails\
**Created:** [February 4, 2008, 9:32am UTC](https://www.ruby-forum.com/t/transactional-services-on-ror/128014 "2008-02-04T09:32:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bcurtu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/a88e4f/32.png) [@bcurtu](https://www.ruby-forum.com/u/bcurtu)\
**Post date:** [February 4, 2008, 9:32am UTC](https://www.ruby-forum.com/t/transactional-services-on-ror/128014/1 "2008-02-04T09:32:13Z")

</div>

Hi there,

I’m pretty new in RoR. I have to deal with 2 different objects from  
the model, and to do some updates on them… How can I work in an  
transactional scope? I mean, if second fails, the first rolls back.

Where do I have to put this code? In the controller, in the model, or  
is there any kind of service layer?

Thanks

---

<div class="post-metadata">

**Author:** ![bcurtu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/a88e4f/32.png) [@bcurtu](https://www.ruby-forum.com/u/bcurtu)\
**Post date:** [February 4, 2008, 3:08pm UTC](https://www.ruby-forum.com/t/transactional-services-on-ror/128014/2 "2008-02-04T15:08:25Z")

</div>

Broadly speaking, this is a business decision so it belongs where the  
BL resides – in the model layer. Depending on how your models are  
related, some of that may be taken care of for you through the  
association proxies. For example, if Header has\_many :details (Detail  
belongs\_to :header) then…

…  
@header = Header.new( … )  
@detail = @header.details.build( … )  
@header.save

The @header.save above will create the header and detail records  
wrapped in a DB connection.

If you want more explicit control over the transaction then you can  
use the #transaction method of the ActiveRecord (model) objects.

Header.transaction do  
header.update\_attributes( … )  
detail.update\_attributes( … )  
end

For more info check the Rails API here:

> **[ActiveRecord::Transactions::ClassMethods](https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#M001115)**
>
> Active Record Transactions Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action.
