How to serialize - deserialize params hash object?

2019-04-11 22:53发布

问题:

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?

回答1:

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"}


回答2:

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.