Serialized hashes with partial_updates in Rails 2.1

June 2, 2008

In Rails 2.1, they added partial updates - which is a great idea and a long time coming. This makes ActiveRecord only updates the parts of a model that has actually changed, and also gives you the ability to see if a field (or a record) has changed since retrieving it from the database. (via model.changed?, model.attribute_changed?, and friends)

There is a gotcha though, If you are using serialized attributes it won't trigger the changed flag unless you assign to it - so if you are doing something like:

model.foo[:bar] = true

ActiveRecord will not realize you have changed anything and it won't get saved. You can get around this by doing something like:

model.foo = model.foo.merge( :bar => true )

Update: You can also tell ActiveRecord it has changed, by calling model.foo_will_change!

Comments

Good catch, thanks.

Nice post! Thank you!

Add comment

Blog Archives

Recent Comments