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.something_serialized[:foo] = 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.something_serialized = model.something_serialized.merge( :foo => true )
2 Roderick van Domburg: June 14, 2008

Good catch, thanks.

3 Finanzamt: June 15, 2008

Nice post! Thank you!

Add comment

About

I'm a programmer and shutterbug living on the West Coast of Canada.

Blog Archive

Recently Heard

A Liberal Educationby New Model ArmyPlayed on 2008/07/16 at 02:35PM
The Two Sides of Monsieur Valentineby SpoonPlayed on 2008/07/16 at 02:32PM
You Weren't Thereby New Model ArmyPlayed on 2008/07/16 at 02:28PM
Powered by Viviti