How to serialize - deserialize params hash object?

房东的猫 提交于 2020-01-01 17:19:09

问题


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.



来源:https://stackoverflow.com/questions/17298747/how-to-serialize-deserialize-params-hash-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!