1

I have an items object which is a hash and I want to store it in database table.

Migration:

t.string :items

Writing:

items: items.to_json

Reading:

@order.items  # returns a string, not a hash as needed.

How do I solve this?

1
  • Everything is an object in Ruby! ;) Commented Sep 28, 2011 at 5:30

1 Answer 1

1

You should add to your model the serialize declaration:

class Xyzzy < ActiveRecord::Base
  serialize :items
end

Optionally you may specify a class:

serialize :items, Hash

so an exception will be thrown if the 'items' object happens to be of some other class.

Also, the column in the database should be declared as :text, because the default length of the :string column is mere 255 characters, and it may be too short for a serialized object.

Sign up to request clarification or add additional context in comments.

Comments

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.