Chris Yeung
Chris Yeung

Reputation: 2723

Storing and Retrieving postgres nested JSONB data type in rails form

I realised there is not much information about how to use rails form to store and retrieve JSON type data. I am currently facing the following problem:

I have a form that creates a nested structure in JSON:

= form_for(@car) do |cf|
    = cf.fields_for :locations do | locations_f |
        = locations_f.fields_for :primary_location do | primary_location_f |
            .sm-col.md-col.sm-col-6.px2
                label.inline-block.mb1 District
                = primary_location_f.text_field :district 
            .sm-col.md-col.sm-col-6.px2
                label.inline-block.mb1 Street
                = primary_location_f.text_field :street 

It will generate input HTML tags as such:

<input name="car[locations][primary_location][district]">

<input name="car[locations][primary_location][street]">

I am able to persist it in database after doing params.permit:

params.require(:car).permit([
    locations:[primary_location:[:street, :district]]
])

I also create store_accessor in the model

store_accessor :locations, :primary_location, :other_locations

However, after I persisted the data, I want it to be shown in the text_field what is already persisted in the database. I try to do something like:

= primary_location_f.text_field :district, value: @car.locations['primary_location']['district']

However, it will run into NilClass Error as sometimes @car.locations['primary_location'] may be nil, and error will arise when I call @car.locations['primary_location']['district'].

I wonder what is the best way to store and retrieve JSON data type. And what is a good way when the JSON is nested.

Thanks

Upvotes: 2

Views: 829

Answers (1)

Uzbekjon
Uzbekjon

Reputation: 11813

However, it will run into NilClass Error as sometimes @car.locations['primary_location'] may be nil, and error will arise when I call @car.locations['primary_location']['district'].

Use .try() method.

@car.locations.try(:[],:primary_location).try(:[], :district)

I wonder what is the best way to store and retrieve JSON data type. And what is a good way when the JSON is nested.

I prefer built in JSON store. Similar to what you are using.

Upvotes: 1

Related Questions