views:

78

answers:

1

Hello, I'm looking to learn how to serialize data in Rails 3...

Things I'd like to learn:

  • A. What serialized data looks like (example for photo_id: 123123, photo_name: "Blah)
  • B. How to serialize data in Rails 3
  • C. How to extract serialized data to do something like mydate.photo_id given the above.

Thanks!

A: 

ActiveRecord has this build in: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-serialize

If you specify in your model that an attribute is serialized, then AR transparently handles the serialization/deserialization. When you call the accessor, it'll deserialize on the fly return the Ruby object (hash, array, whatever). Then you can modify the object as you would normally, and when you save the record, it'll re-serialize and store it.

tfe
What's better serializing data or using JSON (like couchDB?)
AnApprentice
Depends on your definition of better. AR serialize is certainly easier to use. But if you need to use the data outside your app (like through an API you might build) then it's better to serialize yourself using JSON, because users of your API are more likely to know what to do with that than YAML.
tfe