0

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

...I really did not expect that to work since it seems like a String on the model. I guess I need to read up on setters! Glad it does!
You saw that string because you were setting an array on a string attribute and rails serialized the array by default (you saw the resulting value after being serialized). With this setter, you actually control the array as it came from the request and then serialize it the way you want instead, that's why it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.