Rails 3.2,保存序列化哈希不会保存number_with_delimiter()
看来,在Rails 3.2.21中,保存序列化哈希无法保存来自一个特定NumberHelper, helper.number_with_delimiter
在Rails 3.2应用程序中,在模型Foo中我有:
serialize :stuff, Hash
在控制台中:
f = Foo.create f.stuff = { a: "aaaa", b: 1111, c: helper.number_with_delimiter(123456) } => {:a=>"aaaa", :b=>1111, :c=>"123,456"} # so far so good f.save! f.stuff => {:a=>"aaaa", :b=>1111, :c=>123456} # c should be a STRING
它与helper.number_to_currency()
一起正常工作。
如果我设置c: String.new(helper.number_with_delimiter(123456))
,它就可以工作。
这是一个Rails错误,或者我做错了什么?
是的,这是一个Rails(ActiveSupport)错误,最终在Rails 4.2.1中得到修复。 从4.2.1发行说明:
修复了AS :: SafeBuffer的往返问题,其中类似基元的字符串将被转储为基元
当您使用helper.number_with_delimiter
,生成的对象看起来和行为类似于String,但实际上它是一个ActiveSupport::SafeBuffer
。
helper.number_with_delimiter(123456).class # => ActiveSupport::SafeBuffer < String
当你使用:
serialize :stuff, Hash
这意味着Rails使用YAML格式将数据保存到数据库。 SafeBuffer中存在一个错误,导致像"123"
这样的SafeBuffers被错误地转换为整数(即123
)而不是在保存和加载到YAML时保留字符串。
同样,现在从Rails 4.2.1开始修复。 你可以在这里看到修复:
https://github.com/rails/rails/commit/debe7aedda3665702d1f99a3ffb4a123a6c44e9c
- 具有嵌入式ID和侧载的Ember-Data和Active Model Serializer的has_many配置
- 使用active_model_serializers序列化模型数组
- Ember Data属于协会(JSON格式?)
- 使用active-model-serializers错误地为act-as-taggable标签加载JSON
- 版本控制ActiveModel :: Serializer
- 强制活动模型序列化程序返回关联
- <NoMethodError:#Record :: ActiveRecord_Relation的未定义方法`read_attribute_for_serialization':
- Rails Active Model Serializer – has_many并访问父记录
- 在Rails中使用ActiveModel :: Serializer – JSON数据在json和index响应之间有所不同