Create Accessors for JSONB column data in Rails
I was recently reading about the ActiveRecord::Store API and just today, I got the chance to use it. It's a really great API for working with serialized data in Rails.
Let's consider the following model Geolocation
, with a jsonb
column data
. The contents of the data
column look something like this -
The store_accessor
creates getters and settings for coordinates
.
In my case, I have nested data that I'd like to create accessors for - latitude
and longitude
. From what I could find, this API doesn't support nested data yet, so we have to bring in a helper from ActiveModel::Attributes. We declare the coordinates
portion as a jsonb attribute.
I_Ran_Out_Of_Words_Hopefully_You_Get_My_Point :)
S/O Vlad & LayeredDesignForRailsApplications
https://devdocs.io/rails~7.1/activerecord/store
Tweet