如何序列化 - 反序列化 params 哈希对象? [英] How to serialize - deserialize params hash object?

查看:65
本文介绍了如何序列化 - 反序列化 params 哈希对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该怎么做?我希望能够将 params 对象存储到模型的字符串属性中,并且能够再次将其反序列化为 params 哈希对象,我将如何在 ruby​​ 中执行此操作?或者 Rails 中是否有开箱即用的解决方案?

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 可以序列化文本列中的任何对象使用 YAML.为此,您必须通过调用类方法 serialize 来指定它.这使得在不做任何额外工作的情况下存储数组、散列和其他不可映射的对象成为可能.

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

这篇关于如何序列化 - 反序列化 params 哈希对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆