开发者

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_jso开发者_高级运维n

Reading:

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

How do I solve this?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜