Search code examples
ruby-on-railsruby-on-rails-5simple-form

Adding a custom JSONB text_field tag with simple_form


I have a JSONB type options column on a model in my Rails application and I am in a situation where I need to provide JSONB nested parameters manually for every single form. That's why the official solution proposed here is not an option.

So I might want to have something like:

options[first_name], options[last_name]

for one instance, and a totally different set for another:

options[pet_dog], options[frank_sinatra]

I assume it can well be implemented using something like

= f.text_field :options[pet_dog]

But it's not working.


Solution

  • My solution code looks like this:

    View form:

    = f.simple_fields_for :options do |p|
      - @options.each do |o|
        = p.input o.name.to_sym, input_html: {value: o.default_value}
    

    Controller

    def new
      @options = Model.options
      ...
    end
    
    def create
      @job  = current_user.jobs.build(job_params)
    end
    
    ...
    
    def job_params
      params.require(:job_request).permit(
      ...
      options: get_options)
    end
    
    def get_options
      some_model.options.pluck(:name).map(&:to_sym)
    end
    

    Possibly this will help someone.