Rails ActiveRecord: lock without reload

↘锁芯ラ 提交于 2020-01-07 00:58:50

问题


Can I lock an ActiveRecord object without reloading it?

user = User.find(1)
=> #<User id: 1, name: "Ed" ...>
user.name = "Joe"
=> "Joe"
user.lock!
=> #<User id: 1, name: "Ed" ...>

I could send a raw SQL "SELECT ... FOR UPDATE", but it doesn't seem too clean.


回答1:


I ended up adding a method to ActiveRecord::Base:

ActiveRecord::Base.class_eval do
  def lock_without_reload!
    self.class.lock(true).find(id)
    true
  end
end


来源:https://stackoverflow.com/questions/38211871/rails-activerecord-lock-without-reload

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