开发者

Ruby on Rails Scaffold Serialize

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开发者_StackOverflow中文版, i.e. ruby script/generate scaffold NewClass serialized_property:(WHAT SHOULD GO HERE)? Thanks for any help!


The serialize class method on a model that inherits from ActiveRecord::Base will 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 text type 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):

create_table :accounts do |t|
  t.text :settings
end

Then in your model it should be as simple as adding the call to serialize:

class Account < ActiveRecord::Base
  serialize :settings
end

Then when you call Account.new(:settings => { :big_head_mode => true, :awesome => true }).save Rails will automatically serialize the settings hash 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 serialize in your model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜