选择:multiple =>真的不是保存价值

时间:2014-01-07 09:59:36

标签: ruby-on-rails select form-helpers multiple-select

我试图保存多个选定值,形成由rails helper select生成的多选字段。

  <div class="form-group">
    <%= f.label :available_type, "Available in category" %><br>
    <%= f.select :available_type, options_for_select(Setting.subscription_type, @terminal.available_type), { }, { class: "form-control", :multiple => true, :size => 5    } %>
  </div>

这样渲染(所选值来自之前的尝试,没有“:multiple =&gt; true”属性,完美地运行):

<select class="form-control" id="terminal_available_type" multiple="multiple" name="terminal[available_type][]" size="5">
<option value="Postpaid">Postpaid</option>
<option value="MBB">MBB</option>
<option selected="selected" value="Prepaid">Prepaid</option>
</select>

enter image description here

感谢任何帮助。 :)

修改 我已经尝试将serialize :available_type放入我的终端模型中,dident会更改任何内容。 : - /

编辑2: 我注意到,当我标记它们时,多个选择的字段不会将选项标记为已选中。如果我手动添加所选属性,我会得到这些参数:

{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"RrwWlKk8XlGeC+dTu/w6oSM68e9LcbUFJWTI+eRS9mI=", "terminal"=>{"inndate"=>"2015-01-13", "outdate"=>"", "brand_id"=>"2", "name"=>"iPhone 5c", "available_type"=>["", "MBB", "Prepaid"], "product_number"=>"3r2342", "ean_code"=>"", "navision_nb"=>"324234", "cost_price_map"=>"3200.0", "manual_price"=>"", "sales_info"=>"Just sell!"}, "commit"=>"Submit", "action"=>"update", "controller"=>"terminals", "id"=>"2"}

available_type字段的值为"available_type"=>["", "MBB", "Prepaid"]

我正在使用rails 4.0.2,这是我强大的参数:

# Never trust parameters from the scary internet, only allow the white list through.
def terminal_params
  params.require(:terminal).permit(:inndate, :outdate, :brand_id, :name, :product_number, :navision_nb, :cost_price_map, :manual_price, :sales_info, :available_type)
end

1 个答案:

答案 0 :(得分:9)

最终找到了答案!

这个问题是PG和Rails 4的组合。

首先我需要将列从字符串转换为标记为数组的文本列,如下所示:

class ChangeAvailableTypeOnTerminals < ActiveRecord::Migration
  def up
    change_column :terminals, :available_type, :text, array: true, default: []
  end

def down
    change_column :terminals, :available_type, :string
  end
end

然后我需要将强参数作为终端控制器中的数组来处理,如下所示:

# Never trust parameters from the scary internet, only allow the white list through.
def terminal_params
  params.require(:terminal).permit(:inndate, :outdate, {:available_type => []}, :brand_id, :name, :product_number, :navision_nb, :cost_price_map, :manual_price, :sales_info)
end

更具特色:

:available_type更改为{:available_type => []}

这解决了我的问题。 :)