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?
Querying JSON data PostgreSQL returns a result set in the form of JSON. PostgreSQL provides two native operators -> and ->> to help you query JSON data. The operator -> returns JSON object field by key. The operator ->> returns JSON object field by text.
The JSONB data type stores JSON (JavaScript Object Notation) data as a binary representation of the JSONB value, which eliminates whitespace, duplicate keys, and key ordering.
Because JSONB stores data in a binary format, queries process significantly faster. Storing data in binary form allows Postgres to access a particular JSON key-value pair without reading the entire JSON record. The reduced disk load speeds up overall performance. Support for indexing.
The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; while jsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With