0

I've got a serialized array

class Enviroment < ActiveRecord::Base
serialize :roles, Array

...
t.column :roles, :string, :default=> Array.new

and I would like do things like

Enviroment.find(1).roles.push 'thing'

1 Answer 1

2

Providing such default value will save it's YAML representation as String into the Database and Rails unserializes that back into string. That's why it is not working.

Also, maybe you'd want to use text as the column type, so that your array won't be truncated when it gets longer. In recent Rails syntax, that would be:

t.text :roles

And when you want to store new role into database, you'd have to save the object afterwards (in contrast to has_many association which is automatically saved b/c it's key is in the other table):

e = Environment.find(1)
e.roles.push 'thing'
e.save

Or if it absolutely needs to be oneliner:

Environment.find(1).tap{|e| e.roles.push 'things'}.save
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot!! not sure what's the meaning of text there, but it worked. I guess all the serialized objects should have ':text' type??
Yes. Though I doubt there are any actual restrictions. Only that based on the length of your serialized output, it could get truncated if it won't fit in string type (dependent on database probably).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.