Rails AR readonly!
ActiveRecord has some readonly
features that marks a model (or relation) not to be updated. This way if we try:
irb> user = User.last
=> #<User id: 123, ...>
irb> user.readonly!
=> true
irb> user.update(updated_at: Time.current)
(0.3ms) SAVEPOINT active_record_1
(0.3ms) ROLLBACK TO SAVEPOINT active_record_1
ActiveRecord::ReadOnlyRecord: User is marked as readonly
Then we get a rollback with the readonly
error.
An interesting thing is that the touch
AR method does not respect this readonly
feature (I tested on rails 6.0.4.1), check this out:
irb> user = User.last
=> #<User id: 123, ...>
irb> user.readonly!
=> true
irb> user.touch
(0.3ms) SAVEPOINT active_record_1
User Update (1.4ms) UPDATE "users" SET "updated_at" = $1 WHERE "users"."id" = $2 [["updated_at", "2022-03-08 20:39:40.750728"], ["id", 123]]
(0.2ms) RELEASE SAVEPOINT active_record_1
=> true
Tweet