For Rails versions from 4.2 through 5.1.7 the code below worked fine.
In Rails 5.2, in my Rspec tests, unless I add an extra reload (shown below as a comment), it fails with the exception:
ActionView::Template::Error:
Locking a record with unpersisted changes is not supported.
Use `save` to persist the changes, or `reload` to discard them explicitly.
Since the call immediately before the with_lock is a save (as per the exception message) why would this still trigger an exception unless an extra reload is added right after the save?
# merge into the serialized hash field 'settings' a new hash
def update_settings(hash)
return if hash.class != Hash
return if !hash || (hash.count == 0)
self.save # flush any pending changes
# self.reload # <<<<< WHY MUST THIS BE added for rails 5.2?
self.with_lock do
mysettings = self.reload.settings
# mysettings = self.settings
hash.each do |k, v|
mysettings[k] = v
end
self.update_attribute :settings, mysettings
end
end