jeudi 26 septembre 2019

Rails: Using multiple checkboxes for single field

I have a form with multiple checkboxes and I'd like to combine their values into a string before saving to the database. I've designed my form like:

<%= simple_form_for(@health_profile) do |f| %>

    <% @hp_prior.medications.split(", ").each do |med| %>
        <%= check_box_tag "health_profile[medications][]", med, false, id: med, multiple: true %>
        <label for="<%= med %>"><%= med.capitalize %></label>
    <% end -%>

<% end -%>

In my controller I've changed :medications to accept an array:

def health_profile_params
    params.require(:health_profile).permit(:medications => [])
end

But I run into an issue with the data because the submitted form params come through as:

Parameters: {... "health_profile"=>{"medications"=>["zyrtec for allergies", "advil"]}, "commit"=>"Submit"}

But after calling HealthProfile.new(health_profile_params) the record appears as:

#<HealthProfile:0x007fb08fe64488> {... :medications => "[\"zyrtec for allergies\", \"advil\"]"}

How can I combine these values so that the final @health_profile looks like:

#<HealthProfile:0x007fb08fe64488> {... :medications => "zyrtec for allergies, advil"}



Aucun commentaire:

Enregistrer un commentaire