June 12, 2008

Serialize doesn’t play nice with Rails 2.1 partial updates

Filed under: rails — Casper Fabricius @ 3:03 pm

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 Comments

  1. Is it not possible to mark a fields as “always dirty” so it’s contents are saved everytime?

    Comment by Dan Kubb — June 12, 2008 @ 4:50 pm

  2. 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.

    Comment by Casper Fabricius — June 13, 2008 @ 5:05 pm

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.