ActiveRecord serialize not working properly with Hash column

穿精又带淫゛_ 提交于 2019-12-07 13:21:33

问题


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

This is my model:

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

phone_numbers is a text column like it's required.

Then in the console:

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!


回答1:


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

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?



来源:https://stackoverflow.com/questions/28221692/activerecord-serialize-not-working-properly-with-hash-column

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