ActiveRecord序列化不适用于哈希列 [英] ActiveRecord serialize not working properly with Hash column

查看:98
本文介绍了ActiveRecord序列化不适用于哈希列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ActiveRecord的序列化方法在表列中存储哈希,但无法使其正常工作。我正在使用Rails 4.2.0和RailsApi 0.3.1

I'm trying to store a Hash in a table column, using ActiveRecord's serialize method but I can't make it work. I'm using Rails 4.2.0 and RailsApi 0.3.1

这是我的模型:

class Agreement < ActiveRecord::Base
  serialize :phone_numbers, Hash
end

phone_numbers是一个

phone_numbers is a text column like it's required.

然后在控制台中:

a = Agreement.new(phone_numbers: {"dario" => "12345"})
a.phone_numbers 
=> "{\"dario\"=>\"12345\"}" #(Note this is a string, not a Hash as I would expect)

a.phone_numbers["dario"]
=> "dario" #(Not "12345" as I would expect)

我错过了什么东西吗??谢谢!

Am I missing soemthing?? Thank you!

推荐答案

您显示的行为与序列化呼叫错误,列名错误或完全丢失。例如。 https://gist.github.com/smathy/2f4536d3e59b7a52c855

The behavior you're showing is consistent with the serialize call being wrong, either misnamed column, or missing entirely. Eg. https://gist.github.com/smathy/2f4536d3e59b7a52c855

您在问题中显示的是正确的代码,因此您没有正确地复制粘贴该内容,或者自从添加/更正了<$ c $之后,您没有重新启动Rails控制台。 c>序列化调用?

You're showing the right code in your question, so either you didn't copy-paste that correctly, or perhaps it you haven't restarted your rails console since adding/correcting that serialize call?

这篇关于ActiveRecord序列化不适用于哈希列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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