Search code examples
ruby-on-railsruby-on-rails-4activerecordrails-activerecordjrubyonrails

How to disable tracking of changed attributes in model in active_record


I have a simple model with 3 attributes id, paylod (binary data, big), created_at.

I need to extract a bunch of values from the payload data for further processing which I do in the after_initialize callback method. As the payload can be quite big (~20MB), I want to dispose this data by setting @payload = nil after extracting the necessary information to prevent out-of-memory situations when loading a bunch of entries. Note: The model only reads from the DB, no need to persist any changes.

class Payload < ActiveRecord::Base
  after_initialize do |data|
    # extract required values from binary data
    # ... 

    # dispose big data 
    error.payload = nil
    # at this point error.changed_attributes['payload'] 
    # contains the previous payload data (~20MB)
  end
end

How can I prevent the model of preserving the previous value in the @changed_attributes hash?


Solution

  • If the attribute setter method is overloaded without calling super(), all callbacks are disabled and no changes are tracked.

    def payload= ( new_payload )
      @payload = new_payload
    end
    

    In this use-case with a read-only model this works fine. Just be aware that the model also isn't marked dirty either and other side-effects may occur.