【问题标题】:How to stop rails from parsing json postgresql field to hash如何阻止rails将json postgresql字段解析为哈希
【发布时间】:2015-03-17 14:10:45
【问题描述】:

我正在寻找一种方法来告诉 rails 将 json 和 jsonb 数据从 postgresql 列解析到不同的类,或者干脆阻止它解析为哈希,因为我不会使用哈希。

我用read_attribute_before_type_cast, 但是类型转换对我的应用程序来说是浪费的。

谢谢

【问题讨论】:

  • 尝试指定String 类型:serialize :your_field, String

标签: ruby-on-rails json postgresql activerecord


【解决方案1】:

这是我的发现,它不完整但解决了我的问题。我编写/找到了一个序列化程序来处理 json 列。

在模型中:

serialize :profile, HashSerializer

序列化器是这样定义的:

class HashSerializer
  def self.dump(hash)
    hash.to_json
  end

  def self.load(hash)
    (hash || {}).with_indifferent_access
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-13
    • 2019-04-04
    • 2012-02-22
    • 2014-07-10
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 2020-10-29
    相关资源
    最近更新 更多