2

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi how would you use store to achieve it? How can it retrieve the data to the form?
The form simply calls accessors to your fields, so just add corresponding store_accessors. As for json with levels deeper than 1 I would write loops in the view.
Thanks. Will you be able to write an example to help me understand better? Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.