Rails 3 ActiveRecord Transactions

喜欢而已 提交于 2020-01-01 12:05:36

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/5560731/rails-3-activerecord-transactions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!