krn
krn

Reputation: 6815

Ruby on Rails object serialization

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?

Upvotes: 1

Views: 313

Answers (1)

Arsen7
Arsen7

Reputation: 12820

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.

Upvotes: 1

Related Questions