Jake Smith
Jake Smith

Reputation: 2813

Rails - strong parameters - string array column - form

String array in form and controller

I'm using Rails 5 and Ruby 2.3.1

I'm having trouble figuring out how to have a form allow me to add strings to an array on one of my models with one input field per element in the array. For updating an existing record, I'd like a separate input field to be present for each element in the array at that time.

I'd like for the form for a new record to allow me to add one or many elements to this array using a separate input field for each element I decide to add as well.

How would I go about this? I can handle adding inputs with jquery, but I don't know how to use the rails form builder class to do this.

This column is just a string array.

Here is what is currently NOT working:

<!-- _form.html.erb -->
...
  <%= f.label :details %>
  <% @project.details&.each do |detail| %>
      <%= f.text_field :details, 
                       name: 'details[]', 
                       class: 'form-control', 
                       value: detail %>
  <% end %>
...

Here is what I have in my controller:

...
private

  def thing_params
    params.require(:thing).permit(..., details: [])
  end
...

At this point, if I break in the create controller action and inspect the parameters, the params[:details] object has what I would expect (an array of strings). However, if I just print out params, permitted is false and if I print out thing_params, details is not included in the hash.

Does anyone see what I'm doing wrong?

I also suspect that using name: 'details[]' is wrong in the form and have the feeling that only the last one will come in if I get that far...

Upvotes: 0

Views: 1500

Answers (1)

Jake Smith
Jake Smith

Reputation: 2813

Don't you just love trying to solve a problem all day, spend a bunch of time writing up a stackoverflow question after you throw in the towel, only to figure it out 5 minutes later? I sure do.

What needed to change was what I put in the form:

<!-- _form.html.erb -->
...
  <%= f.label :details %>
  <% @project.details&.each do |detail| %>
      <%= f.text_field :details, 
                       # name: 'details[]', (this is what I had before)
                       name: 'thing[details][]', 
                       class: 'form-control', 
                       value: detail %>
  <% end %>
...

Upvotes: 3

Related Questions