Jacob
Jacob

Reputation: 1672

Postgresql JSON column as HashWithIndifferentAccess

I have a table called 'my_models' with a 'json' column called 'settings'.

I also have the following model:

class MyModels < ActiveRecord::Base
end

The 'settings' attribute of an 'MyModels' instance is a Hash.

Is it possible to configure 'MyModels' to type cast the raw column value of 'settings' to a HashWithIndifferentAccess instead of Hash?

Upvotes: 5

Views: 2310

Answers (1)

ichigolas
ichigolas

Reputation: 7735

Serialize alone wont work here since HashWithIndifferentAccess does not respond to both load and dump methods, but you can do this:

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

See also Custom serialization for fields in Rails

Upvotes: 7

Related Questions