Store accessor for nested JSON in Rails

Store accessor for nested JSON in Rails

Today we will look at a handy Rails tool called store_accessor. store_accessor can be used with PostgreSQL(hstore/jsonb), or MySQL (5.7+ json) to directly access your data without clogging your models. It also allows us to use dirty methods on these attributes.

A simple usage of store_accessor:

Let's say we have a model Payments with a jsonb column called details

hash

The details column will have data that looks something like this

hash

Now to access and use mode in the details object one can use store_accessor with options like suffix/prefix.

hash

Note that store accessor does not support nested data, only top-level key-value pairs. But we can take help of attribute method of rails to access nested values. Just define extra as an attribute and voila.Now, you can also use dirty methods on it!

hash