Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 ActiveRecord Transactions

I have a model method that I'd like to call from various 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?

like image 213
Dex Avatar asked Apr 06 '11 02:04

Dex


1 Answers

In your current setup, if read_at gives an error, it will still continue onto the 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

By using transactions, you can be assured that either all your database calls(within the transaction block) will be persisted to the database, or none at all.

like image 86
Mike Lewis Avatar answered Oct 05 '22 20:10

Mike Lewis