5

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?

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

4 Comments

Ahh a custom serializer. I always thought their were limited to text columns, but it works great!
While this works, it should probably be noted that it prevents you from editing the hash directly. For example: model.my_hash_attribute = {} model.my_hash_attribute[:test] = "abc" model.my_hash_attribute # {} Doesn't work like most people would expect it to.
with a cursory look at HashWithIndifferentAccess, I can't figure out why calling .with_indifferent_access on a jsonb attribute breaks writing to it.
See stackoverflow.com/a/28683140/3453300 for an answer which allows modifying the hash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.