Stop ActiveRecord saving a serialized column even if not changed

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-29 10:44:49

What I ended up doing, even though it's not really an answer to the original question, is the following:

class Import < AR::Base
  belongs_to :storage

class Storage < AR::Base
  serialize :data

...i.e. moving the data column into a model of its own, and associate that with the original model. Which is actually conceptually somewhat cleaner.

Here is an ugly monkey patch solution:

module ActiveRecord
  module AttributeMethods
    module Dirty
      def update(*)
        if partial_updates?
          # Serialized attributes should always be written in case they've been
          # changed in place.  Unless it is 'spam', which is expensive to calculate.
          super(changed | (attributes.keys & self.class.serialized_attributes.keys - ['spam']))
        else
          super
        end
      end
      private :update
    end
  end
end
class Foo < ActiveRecord::Base
  serialize :bar
  serialize :spam


  def calculate_spam
    # really expensive code
  end

  def cache_spam!
    calculated_spam = calculate_spam
    @changed_attributes['spam'] = [spam, calculated_spam]
    self.update_attribute(:spam, calculated_spam)
  end
end

You will have to remember to call cache_spam!, or your serialized attribute will never be saved.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!