Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Multiple options into a single string

I'm trying to make so that the user sees a number of options (I'm currently trying with check boxes) as selects multiple items, then turns into a single string joined by commas when the user submits it, ex:

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

where :answer is an attribute in my Answer model and description is an attribute in my Option model, if multiple options are selected I want them to be saved as a single string like so:

"description1,description2,description3"

in order to save it to a single column in my database, how can I achieve this?

like image 776
IvanH Avatar asked May 08 '26 07:05

IvanH


1 Answers

You can create multiple checkboxes adding them the multiple option, this way you can have:

<%= 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 you'll also need to specify the false option to "can get rid" of all the unwanted values a group of multiple check_boxes generates, something like ["0", "0", "second", "0", "third"], that because of the unchecked default values, so, with the last parameter in your check_box helper, you get just ["second", "third"].

So, now having just an array is easier to join those values before persiting the object into the database, this can be done directly in the controller if you want:

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

Here you get the values from the params['answer'], the form, and specifically the checkboxes you've created, as it's an array you can use join to join them with a comma ,, so you'll get "second,third", and this way you can set the answer attribute for your Answer model with multiple checkboxes.

like image 100
Sebastian Palma Avatar answered May 10 '26 20:05

Sebastian Palma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!