Postgresql JSON列为HashWithIndifferentAccess

Jac*_*cob 5 ruby postgresql activerecord json ruby-on-rails-4

我有一个名为'my_models'的表,其中一个名为'settings'的'json'列.

我也有以下型号:

class MyModels < ActiveRecord::Base
end
Run Code Online (Sandbox Code Playgroud)

"MyModels"实例的"settings"属性是Hash.

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

nic*_*oga 7

单独序列化不会在这里工作,因为HashWithIndifferentAccess不响应这两者loaddump方法,但你可以这样做:

class THEModel < ActiveRecord::Base
  def my_hash_attribute
    read_attribute(:my_hash_attribute).with_indifferent_access
  end
end
Run Code Online (Sandbox Code Playgroud)

另请参阅Rails中字段的自定义序列化

  • 虽然这有效,但应该注意它可以防止您直接编辑哈希.例如:model.my_hash_attribute = {} model.my_hash_attribute [:test] ="abc"model.my_hash_attribute#{}不能像大多数人期望的那样工作. (11认同)