Serialize doesn’t play nice with Rails 2.1 partial updates

One of the new features in Rails 2.1 is dirty models, which in turn allows for partial updates.

However, this can result in fields not being updated in the database, if you do not use the conventional setter attributes. One unconventional way of updating an attribute, is to change the object of a serialized attribute – typically a Hash.

If I have this model:

class Page < ActiveRecord::Base
  serialize :properties, Hash
end

- then this code will not update my serialized field in the database:

p = Page.first
p.properties[:color] = 'fff'
p.save

- since I haven't assigned anything to properties, but just changed the contents of the Hash inside properties.

To get the properties field properly updated in the database, I need to call properties_will_change! like this:

p = Page.first
p.properties_will_change!
p.properties[:color] = 'fff'
p.save

I wonder if this is a bug or a feature ... ?

2 thoughts on “Serialize doesn’t play nice with Rails 2.1 partial updates

  1. Dan, I’m not sure about that. I’ve looked through the code, and I haven’t found anything. Perhaps by calling will_change! in before_save something like that can be achieved.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>