开发者

Ruby on Rails object serialization

开发者 https://www.devze.com 2023-04-09 02:54 出处:网络
I have an items object which is a hash and I want to store it in database table. Migration: t.string :items

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

精彩评论

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

关注公众号