Rails:序列化数据库中的对象? [英] Rails: Serializing objects in a database?
问题描述
我正在寻找有关序列化数据库中对象的一些常规指导.
I'm looking for some general guidance on serializing objects in a database.
- 什么是序列化对象?
- 在数据库中序列化对象的一些最佳实践方案是什么?
- 在数据库中创建列时使用什么属性,以便可以使用序列化的对象?
- 如何保存序列化对象?
- 以及如何访问序列化对象及其属性? (使用哈希吗?)
推荐答案
在计算机科学中,在数据存储和传输的上下文中,序列化是将数据结构或对象转换为位序列的过程,以便可以将其存储在文件,内存缓冲区中,或者跨对象传输.网络连接链接将在以后在相同或另一台计算机环境中恢复". (请参见 http://en.wikipedia.org/wiki/Serialization )
In computer science, in the context of data storage and transmission, serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file, a memory buffer, or transmitted across a network connection link to be "resurrected" later in the same or another computer environment. (see http://en.wikipedia.org/wiki/Serialization)
-
因此,序列化的对象(在ActiveRecord的上下文中)是对象的文本/字符串表示形式(使用YAML编码).序列化后,您可以将(几乎)任何Ruby对象保存在一个数据库字段中.
So serialized objects (in the context of ActiveRecord) are text/string representations of objects (encoded using YAML). When serialized, you can save (almost) any Ruby object in a single database field.
如果您有一些复杂的对象需要保存在数据库中并且不需要根据序列化属性的内容检索记录,则可以使用序列化.例如,我使用它们来存储Web应用程序用户的首选项:这些首选项基本上是我想保存在单个db字段中的哈希.
You can use serialization if you have somewhat complex objects that you need to save in a database and you don't need to retrieve records based on the contents of a serialized attribute. I used them for example for storing preferences for users of a webapp: the preferences were basically hashes that I wanted to save in a single db field.
3./4./5.按照Marc-AndréLafortune的建议,使用 ActiveRecord :: Base.serialize :
3./4./5. Use ActiveRecord::Base.serialize as Marc-André Lafortune suggested:
class User < ActiveRecord::Base
serialize :preferences
end
u = User.new
u.preferences = {:show_tooltips => true, :use_extended_menu => false, ...}
u.save
# ...
u = User.find(23)
u.preferences # => {:show_tooltips => true, :use_extended_menu => false, ...}
这篇关于Rails:序列化数据库中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!