ruby - Postgresql JSON 列作为 HashWithIndifferentAccess

标签 ruby json postgresql activerecord ruby-on-rails-4

我有一个名为“my_models”的表,其中有一个名为“settings”的“json”列。

我还有以下模型:

class MyModels < ActiveRecord::Base
end

“MyModels”实例的“设置”属性是一个哈希。

是否可以将“MyModels”配置为将“settings”的原始列值类型转换为 HashWithIndifferentAccess 而不是 Hash?

最佳答案

因为 HashWithIndifferentAccess 不会同时响应 loaddump 方法,所以单独序列化在这里不起作用,但您可以这样做:

class THEModel < ActiveRecord::Base
  def my_hash_attribute
    read_attribute(:my_hash_attribute).with_indifferent_access
  end
end

另见 Custom serialization for fields in Rails

关于ruby - Postgresql JSON 列作为 HashWithIndifferentAccess,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24389018/

相关文章:

ruby-on-rails - 在 Rails 中运行 bundle exec rspec spec/requests/static_pages_spec.rb 时出错

mysql - crontab显示mysql错误

javascript - 为什么 [object Object] 提到 "object"两次?

json - 多个json字符串的分隔符

postgresql - Postgres。角色 "root"不存在。尝试 pg :pull database from Heroku 时

ruby-on-rails - `AdapterNotSpecified` 数据库未配置

java - 生成具有列表和字符串类型属性的 JSON 模型

postgresql - 从 Docker 容器内的 PostgreSQL 数据库生成转储文件

python - Django 和 Postgres 事务回滚

ruby-on-rails - Rails 存在吗?不区分大小写