Rails 3 ActiveRecord Transactions

I have a model method that I would like to call from different controllers. It looks something like this:

def Post < ActiveRecord::Base
    def read!
      self.read_at = Time.now
      self.save
      self.thread.status = Status.find_by_name("read")
      self.thread.save
    end
end

In my controller, if I call @post.read!, will this rollback on any errors?

+5
source share
1 answer

In your current setup, if read_at gives an error message, it will still continue to execute code that executes thread.status, for example.

You want to use ActiveRecord transactions :

def read!
  transaction do
    self.read_at = Time.now
    self.save
    self.thread.status = Status.find_by_name("read")
    self.thread.save
  end
end

Using transactions, you can be sure that either all database calls (inside the transaction block) will be stored in the database, or not at all.

+21

All Articles