问题
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