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:
- Append the user_id integer (from 1 to 9999) serialized in a column “invites”
- Retrieve all the user id’s back from the User.invited column ( deserialize it ? )
From the fine manual:
So, if you want to store an array of integers as a serialized object, then:
You’d want the
invitescolumn to be atextcolumn in the database (notstring!) to avoid running into size issues.Then you can treat
user.invitesas a plain Array: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.
serializeuses 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.