Opt out of `touch` bumping lock_version?

Anyone else find it surprising that touch bumps OptimisticLocking’s lock_version ? It was added as a feature back in 2011, but I’m not sure I see why that would be useful.


One example where this is causing problems is in forms that accept ActiveStorage uploads. Say I have a Post editing form which accepts some text fields for the post title & body, and an ActiveStorage image upload. Post has a lock_version column to try and avoid any stale reads. If I submit the form with an image, then tweak the text fields and submit again, there’s a good chance of hitting StaleObjectError because AnalyzeJob has asynchronously run on the image and touched the Post, bumping its lock_version.


There’s some mention of this being surprising behaviour in Touch model records after ActiveStorage::Blob is analyzed by natematykiewicz · Pull Request #45579 · rails/rails · GitHub , but I don’t think it got anywhere.

Presumably we still want to keep the current behaviour as a default? Like I said, I don’t really get the use-case, can anyone suggest why it might be desirable?

Perhaps we could tweak locking_enabled?'s method signature? eg if we passed attempted_action to the locking_enabled method here - rails/activerecord/lib/active_record/locking/optimistic.rb at 23729cec4eb591995f6ac6e88e49fd444e011f3c · rails/rails · GitHub - then I could opt out of the lock_version bumps from touch methods:

class ApplicationRecord
  def self.locking_enabled?(attempted_action: nil)
     attempted_action != "touch" && super
  end
end