Jeremy Thomas
Jeremy Thomas

Reputation: 6694

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"}

Upvotes: 0

Views: 67

Answers (1)

arieljuod
arieljuod

Reputation: 15848

Implement a custom setter for the attribute on your model:

def medications=(value)
  value = value.join(', ') if value.is_a?(Array)
  write_attribute :medications, value
end

Upvotes: 2

Related Questions