Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

ruby on rails - Stop ActiveRecord saving a serialized column even if not changed

This is very similar to Rails partial updates problem with hashes , but the question has not really been answered IMHO.

The problem is this: I have a model with a serialized column:

class Import < AR::Base
  serialize :data

In my case, this data will, and should, not change after the first save/creation of the model. So I want to disable the feature of AR that always saves serialized columns (which is normally a good idea, as it can't detect those changes). I want to disable the saving because the data can be quite large, and the model will be updated frequently.

I've already tried monkeypatching into ActiceRecord::AttributeMethods::Dirty like this:

class Import
  def update(*)
    if partial_updates?
      super(changed | (attributes.keys & (self.class.serialized_attributes.keys - ["data"])))
    else
     super
   end
 end

but this seems to have no effect. Anybody got a better idea ?

This is under Rails 3.0.12

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...