Rails:对单个字段使用多个复选框

问题描述 投票:-1回答:1

我有一个带有多个复选框的表单,我想在保存到数据库之前将它们的值组合成一个字符串。我的表单设计如下:

<%= 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 -%>

在我的控制器中,我将:medications更改为接受数组:

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

但是我遇到了数据问题,因为提交的表单参数通过以下方式出现:

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

但是在调用HealthProfile.new(health_profile_params)之后,记录显示为:

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

如何合并这些值,以便最终的@health_profile看起来像:

#<HealthProfile:0x007fb08fe64488> {... :medications => "zyrtec for allergies, advil"}
ruby-on-rails forms checkbox
1个回答
2
投票

为模型上的属性实施自定义设置器:

def medications=(value)
  value = value.join(', ') if value.is_a?(Array)
  write_attribute :medications, value
end
© www.soinside.com 2019 - 2024. All rights reserved.