I wanted to store arbitrary nested data structures in a jsonb column and be able to retrieve and work with that data seemlessly within a Rails application. There are several tutorials covering different aspects of this, but none felt complete to me.
For this example we'll be working with a User
model that can define surveys. Each survey consists of n
multiple choices questions, and each question can have between two and ten answer options.
In this case we use Postgresql's JSONB support to store the data, but you could also use other forms of serializing such as a text
column and Rails' default YAML serializing. JSONB is chosen in this case because it leaves open the possiblity of querying the data with SQL. Also, apparently serializing to JSON is much faster.[1]