javascriptarraysruby-on-railsform-helpers

How to add a tags input functionality in rails form or how to add array to input field?


I am building a form where I want to add the user to add tags in the form.

I have completed the functionality but from the front-end only and things got complex to handle.

I am using Ruby on Rails in backend and html css js jQuery in frontend.

So far the user can add the tags in the way I want but I didn't find any way of sending the tags as an array in the form.

Is there any way of sending array with forms in input or in rails forms or something else?

As I said, I don't know how to send array with form so I am converting that array to string to store it in input field and then back to array using split with comma to print it on form.

But user can add , in input and I don't want to split the string with that comma so that's not the good way of using string!

If you have any tutorial or link where I can find out how to send that in backend then I will be thankful to you...

Thanks


Solution

  • HTML [] convention.

    Array:

    <input type="textbox" name="course[track_codes][]", value="a">
    <input type="textbox" name="course[track_codes][]", value="b">
    <input type="textbox" name="course[track_codes][]", value="c">
    

    Params received:

    { course: { track_codes: ['a', 'b', 'c'] } }
    

    Another option you have is using:

    f.input :name, input_html: { multiple: true }
    

    or if you have the simple_form_for gem:

    f.input_field :name, multiple: true