I was looking through some Rails code and noticed that one of the classes in models contained the following line: serialize :some_property. I wanted to scaffold a new class that will contain a serialized property, but I don’t know how to do it exactly. What type should I declare for the serialized property, i.e. ruby script/generate scaffold NewClass serialized_property:(WHAT SHOULD GO HERE)? Thanks for any help!
Share
The
serializeclass method on a model that inherits fromActiveRecord::Basewill take that column/attribute and turn it into YAML on save, and do the opposite on load. It’s great for keeping a basic array or hash object in your model.Rails only requires that you use a
texttype column in your database/migration for the serialized field. So in your migration, just make sure you have the following for your serialized field (in this case,settings):Then in your model it should be as simple as adding the call to
serialize:Then when you call
Account.new(:settings => { :big_head_mode => true, :awesome => true }).saveRails will automatically serialize thesettingshash into YAML and persist it in your database.And just to be clear, scaffolding has nothing to do with the matter. After generating the scaffold, you’ll still need to add the call to
serializein your model.