Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 956
Jacob Avatar asked Jun 24 '14 14:06

Jacob


People also ask

How do I query a JSON column in PostgreSQL?

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.

What is a Jsonb column?

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.

Is Postgres Jsonb fast?

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.

What is the difference between JSON and Jsonb?

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.


1 Answers

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

like image 168
ichigolas Avatar answered Sep 27 '22 21:09

ichigolas