newbie: append serialized integers into database column and retrieve them back

前端 未结 1 1794
囚心锁ツ
囚心锁ツ 2021-01-07 07:30

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,

相关标签:
1条回答
  • 2021-01-07 08:03

    From the fine manual:

    serialize(attr_name, class_name = Object)

    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.

    Then you can treat user.invites as a plain Array:

    user.invites = [ 1, 2, 3 ]
    user.invites.push(11)
    

    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.

    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.

    0 讨论(0)
提交回复
热议问题