0

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...

1 Answer 1

3

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 %>
...
Sign up to request clarification or add additional context in comments.

Comments

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.