Custom save method on a model?

Hi everybody,

In my code I use a transaction to ensure that an update takes place on
two tables at the same time:

begin
Transfer.transaction do
transfer.save!
user.save!
end
rescue
#handle errors
end

At the moment I do this in my controller, but since it is actually an
action on my model, this feels wrong. I think I should create a new
method on my model that saves itself and the other model using a
transaction. So e.g.:

class Transfer < ActiveRecord::Base
def save_with_user_update
Transfer.transaction do
transfer.save!
user.save!
end
return true
rescue
#handle errors
return false
end
end

Would this be considered good practice? Should I also mark save and
save! as protected to enforce the use of my own method? Or to take it
one step further: I could alias the regular save and save! and replace
them by my own versions. Maybe that’s a bit too much tinkering?

I’m a Rails newbie, so I’m interested to hear what more experienced
developers think about this. Am I on the right track?

cheers,
Kees-Jochem

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs