问题描述
如何可以存储连载中的数据库列整数(用户ID的范围从1到9999),并获取他们回来?
How Could I store integers (user id's ranging from 1 to 9999) serialized in a database column and retrieve them back?
在我的用户模式,我有邀请列,
In my User model I have invites column,
User model
serialize: invites
invites = text field
现在我想要做的两件事情:
Now I'm trying to do 2 things:
- 追加USER_ID整数(从1到9999)连载的专栏邀请
- 检索来自User.invited列中的所有用户ID的背部(反序列化?)
推荐答案
在精细的手工:
连载(attr_name,将class_name =对象)
如果你有需要被保存到数据库中作为对象,并检索为同一个对象的属性,然后指定使用这种方法,其属性的名称,它会被自动处理。序列化是通过YAML完成。如果将class_name
被指定,序列化的对象必须是在检索该类或 SerializationTypeMismatch
将得到提升。
If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, then specify the name of that attribute using this method and it will be handled automatically. The serialization is done through YAML. If class_name
is specified, the serialized object must be of that class on retrieval or SerializationTypeMismatch
will be raised.
所以,如果要存储一个整数数组作为序列化对象,则:
So, if you want to store an array of integers as a serialized object, then:
class User < ActiveRecord::Base
serialize :invites, Array
#...
end
您会希望在邀请
列是一个文本
列在数据库中(不是字符串
!),以避免运行到大小的问题。
You'd want the invites
column to be a text
column in the database (not string
!) to avoid running into size issues.
然后你可以把 user.invites
作为一个普通数组:
Then you can treat user.invites
as a plain Array:
user.invites = [ 1, 2, 3 ]
user.invites.push(11)
这当然不验证的数字是有效的,或者你没有重复(但你可以使用的相反,它也不会从把一个字符串中有prevent你。
That of course doesn't verify that that numbers are valid or that you don't have duplicates (but you could use a Set instead of an Array for that), it also won't prevent you from putting a string in there.
我不建议你这样做,虽然,系列化几乎总是一个错误,以后还会再来咬你。序列化的列数据的不透明的blob至于数据库而言:你不能更新就地,不能查询它,你所能做的就是把它从数据库中,并把它放回去。 连载
使用YAML进行序列化,这就是一个可怕的格式,如果你需要与你的数据库里面的数据序列化的工作;您还可以运行到有趣的编码问题在升级过程。
I don't recommend that you do this though, serialization is almost always a mistake that will come back to bite you later. A serialized column is an opaque blob of data as far as the database is concerned: you can't update it in-place, you can't query it, all you can do is pull it out of the database and put it back. serialize
uses YAML for serialization and that's an awful format if you need to work with your serialized data inside the database; you can also run into interesting encoding issues during upgrades.
你最好设立一个传统的关联表和单独的样板(可能使用的)来处理这种情况。
You're better off setting up a traditional association table and a separate model (possibly using has_many ... :through =>
) to handle this situation.
这篇关于新手:追加系列化整数到数据库列和检索他们回来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!