Rails: multiple options on one line

I'm trying to get the user to see multiple options (I'm currently trying to check boxes) when he selects multiple items and then turns into a single comma-concatenated string when the user submits it, like this:

<%= f.check_box :answer %><%= option.description %>
<%= f.check_box :answer %><%= option.description %>
<%= f.check_box :answer %><%= option.description %>

      

where: response is an attribute in my response model and description is an attribute in my options model if multiple options are selected. I want them to be stored as one line, for example:

"description1,description2,description3"

      

to store it in one column in my database, how can I achieve this?

+3


source to share


1 answer


You can create multiple checkboxes by adding a parameter to them multiple

, this way you can:

<%= f.check_box :answer, { multiple: true }, 'first', false %>First
<%= f.check_box :answer, { multiple: true }, 'second', false %>Second
<%= f.check_box :answer, { multiple: true }, 'third', false %>Third

      

Note that you also need to specify an option false

to "can get rid" of all unwanted values ​​generated by a group of multiple check_boxes, something like ["0", "0", "second", "0", "third"]

that due to unchecked defaults , so with the last parameter in your helper check_box

you will only get ["second", "third"]

.



So now, having only an array, it's easier to attach these values ​​before transferring the object to the database, this can be done directly in the controller if you want:

@answer = Answer.new(answer_params)
@answer.answer = params['answer']['answer'].join(',')

      

This is where you get the values ​​from params ['answer'], the form, and in particular the checkboxes you created, as this is an array that you can use join

to concatenate with a comma ,

, so you get "second, third", and thus you can set the answer attribute on your multiple checkbox answer model.

+1


source







All Articles