简体   繁体   中英

How to serialize - deserialize params hash object?

how would I do such a thing? I want to be able to store the params object into a string attribute of a model, and be able to deserialize it into params hash object again, how would I do this in ruby? or is there an out of the box solution in rails?

Active Record can serialize any object in text columns using YAML . To do so, you must specify this with a call to the class method serialize. This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work.

class User < ActiveRecord::Base
  serialize :preferences
end

user = User.create(preferences: {background: "black", display: "large"})
User.find(user.id).preferences 
# => {background: "black", display: "large"}

Mori's answer is correct, but if your data type in the model is truly a string, it may not fit. Suggest you use text instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM