How to configure simple_form for json hested hash

I have some nested data:

@preset = Preset.new #fields is a postgres json data type @preset.fields = {'primary_category' => {'category_id' => 57882}} 

I would like to have the same nested structure stored in POST params[:preset][:fields] from the submit form, so I have this in my part:

 <%= text_field_tag("preset[fields][primary_category][category_id]",nil) -%> 

The simple form does not know how to deal with new postgres types like hstore or json. In my case, I really do not need this to check or to determine the data type. Is there a way I can extend SimpleForm to skip the detection of column types and just output the same existing bootstrap test pattern that it prints for text fields, but for my arbitrary json nested keys?

It is possible to use this type:

 <%= f.input 'preset[fields][primary_category][category_id]', :as => :json_text_field %> 

Print the same as the helper above, but surrounded by a label, as well as cool div groups, etc.

I have looked at extending the base input class for documentation.

 class JsonTextFieldInput < SimpleForm::Inputs::Base def input "#{@builder.text_field(???, input_html_options)}".html_safe end end 

But this is where I got lost, because I’m not sure what to pass to @builder to bypass checking the attribute name with my own logic to display its hash keys. It also changes only the input of the form, and not the label, which also needs some modification. In any case, I could not go very far, and I could use some recommendations.

+4
source share
1 answer

I use this to input jsonb / json:

 class JsonbInput < SimpleForm::Inputs::StringInput def input() out = ActiveSupport::SafeBuffer.new Hash[object.send(attribute_name).sort].each do | k, v| out << template.content_tag(:div, class: 'group') do template.concat @builder.label(k, object.send(attribute_name), label_html_options) template.concat @builder.text_field(k, input_html_options) end end out end def input_html_options {class: 'string form-control'} end end 

You also need to use store_accessor in your model.

+3
source

Source: https://habr.com/ru/post/1496323/


All Articles