Transactional Services on RoR

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?


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 = ... )
@detail = ... )

The 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( ... )

For more info check the Rails API here: