Question

I am using simple_form and have a following sample tag:

<%= f.input :medical_conditions, :label=>false, :collection => medical_conditons, :as => :check_boxes%>

The collection holds about 100 checkboxes. However, when user only selects 1 or 2, everything is still getting saved to the database like this:

---
- ""
- ""
- ""

medical_conditions is a simple array in my application_helper

def medical_conditons
t = [
    "Allergies/Hay Fever",
    "Diabetes",
    "Heart Surgery"]
return t
end

the medical_conditions field is a :string field.

What do I need to do so that only values that are selected are saved in comma separated manner.

Was it helpful?

Solution

It is not simple_form behavior. It is from Rails. See this: http://d.pr/6O2S

OTHER TIPS

Try something like this in your controller (guessing at how you wrote your create/update methods)...

params[:medical_conditions].delete('') #this will remove the empty strings
@instance.update_attribute(:medical_conditions, params[:medical_conditions].join(','))
#or however you want to save the input, but the key is the .join(',') which will
#create a comma-separated string of only the selected values, which is exactly
#what you're looking for me thinks :-)

If that does the trick for you, I'd consider making a private helper method that formats the params for you so that you can use it in #create, #update, or wherever else you need it. This should keep things a little cleaner and more "rails way-ish" in your crud actions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top