I originally posted this to the Rails GitHub issue tracker (my apologies) here: https://github.com/rails/rails/issues/23490. I’m now posting it in the correct place.
I am trying to mutate objects in memory without persisting them to the database (we always mutate the object, then we use it for a few business purposes, and then we only sometimes save the change, other times we reject them). Active record already supports modifying existing records in memory and adding new records in memory, which only get persisted to the database on save. However, deletions seem to always happen immediately. I believe this is the same idea that was put forth on this issue: #6994
The simplest example I can extract from my code would be something like this:
class CommunicationSetting < ActiveRecord::Base has_one :trigger, autosave: true end class Trigger < ActiveRecord::Base belongs_to :communication_setting, touch: true end c = CommunicationSetting.find(1) c.trigger # => #<TriggerA:0x007faeba3dfa70 id: 1, communication_setting_id: 1> # The following line runs a DELETE query on the database c.trigger.delete # or destroy # I want the delete query to run here, in case I decide to discard the changes c.save!
I have also tried the
mark_for_destruction method. That works exactly as I would like for the SQL queries. However, the object acts as if the value still exists, so it’s not in a consistent state.
c = CommunicationSetting.find(1) c.trigger # => #<TriggerA:0x007faeba3dfa70 id: 1, communication_setting_id: 1> # No DELETE is run here. Yay! c.trigger.mark_for_destruction # Unfortunately, the trigger still acts as if it is still here c.trigger # => #<TriggerA:0x007faeba3dfa70 id: 1, communication_setting_id: 1> # The DELETE query does run here like I want c.save!
A similar occurrence happens on
has_many associations, but it was simpler to demonstrate on the
has_one because we don’t have to think about the array at the same time.
Another point of reference. This guy on Stack Overflow did a good job explaining the situation:http://stackoverflow.com/questions/11353582/delete-associated-records-when-model-is-saved
I can vouch that the behavior described occurs on Rails version 4.2.5, which is what I’m running in our project.