Ruby-on-rails Rails 3 序列化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3834902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:17:25  来源:igfitidea点击:

Rails 3 Serialize

ruby-on-railsserializationruby-on-rails-3

提问by AnApprentice

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

我正在寻找学习如何在 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.
  • A. 序列化数据是什么样的(例如 photo_id: 123123, photo_name: "Blah)
  • B. 如何在 Rails 3 中序列化数据
  • C. 如何提取序列化数据来做类似上面给出的 mydate.photo_id 的事情。

Thanks!

谢谢!

回答by tfe

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

ActiveRecord 有这个内置: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.

如果您在模型中指定将属性序列化,则 AR 会透明地处理序列化/反序列化。当您调用访问器时,它会即时反序列化并返回 Ruby 对象(散列、数组等)。然后你可以像往常一样修改对象,当你保存记录时,它会重新序列化并存储它。