Working With JSON in Ruby On Rails Models
JSON or Java Script Object Notation is a way of storing data using key/value pairs, it is essentially the exact same thing as a hash or map. In the past I’ve used the JSON in my Rails models in order to simplify my database.
When I was building the Newport Marine Detailing application I decided to use JSON in order to keep track of each appointments services. Ultimately this made my application a lot easier to build because I didn’t have to create a new Services model or associate it with existing models. The corresponding migration looked like this:
add_column :appointments, :services, :jsonb
PostgresSQL offers to JSON data types JSONA and JSONB, I’m not really sure if there are any performance differences or tradeoffs between the two types.
Even though JSON is technically a map the data is stored as a string in our active record model. Before we can actually do anything with our data we need to parse the JSON String into a ruby hash. I’ve found the best way to do this is to create a public method inside of your model where you return a parsed version of the data.
class Appointment < ApplicationRecord
#...
def services_hash
eval(services)
end end
The eval function is pretty cool, it simply takes a string and evaluates it as if it were a piece of Ruby code, this is all made possible via meta programming ie. code writing code ! Now that we have our JSON available as a hash we can start to work with our data at the controller and view level:
<table>
<% @appointment.services_hash.each do |k,v| %>
<tr>
<td> <%= k %> </td>
<td> <%= v %> </td>
</tr>
<% end %>
</table>
Thanks for reading be sure to checkout my Podcast and YouTube channel for all things Ruby!