Hello stranger!

Rails Tip: Dynamic JSON fields

Recently I had the chance to work on a piece of software that required interacting with JSON Arrays. As you may know using native JSON columns in ActiveRecord it’s as simple as using the store_accessor. For example, let’s say we are defining a new column json_object that has to follow this JSON structure:

{"name":"juan perez","age":69}

By using store_accessor in the following way:

store_accessor:json_object,:name,:age

You will define accessors to those two fields that in the end will save those said fields as a JSON to that specific column. Nothing really fancy.

And finally the tags_attributes= method acts as the setter when submitting the form.

With that you can store an array of values to a JSON column. One nice improvement to this Rails application could be to add cocoon to allow adding (and removing) any number of dynamic fields instead of the hardcoded we defined currently.