选择:multiple => true不保存值

Ole*_*røm 5 select ruby-on-rails multiple-select form-helpers

我试图保存多个选定的值,形成由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>
Run Code Online (Sandbox Code Playgroud)

这样渲染(所选值来自先前的尝试,没有":multiple => 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>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

任何帮助表示赞赏.:)

编辑: 我试过把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"}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Ole*_*røm 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
Run Code Online (Sandbox Code Playgroud)

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

# 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
Run Code Online (Sandbox Code Playgroud)

要更具特色:

从改变:available_type{:available_type => []}

这解决了我的问题.:)