collection_select类型字段上的必填字段

时间:2016-03-01 15:24:23

标签: ruby-on-rails forms ruby-on-rails-4 field form-for

我有一个带有简单文本字段的表单,我需要填写表单:

<%= f.text_field :email, :required => true %>

下一个字段是collection_select类型,我想强制用户选择一个选项。我试过了:

<%= f.collection_select(:list_ids, List.where(user_id: current_user), :id, :name, {}, {multiple: true}), :required => true %>

给了我错误:

syntax error, unexpected ',', expecting ')' ..., :name, {}, {multiple: true}), :required => true );@output_... ... ^

没有:required => true选项,代码运行正常。在这种情况下,如何强制用户进行选择?感谢

3 个答案:

答案 0 :(得分:6)

尝试更改此

<%= f.collection_select(:list_ids, List.where(user_id: current_user), :id, :name, {}, {multiple: true}), :required => true %>

到这个

<%= f.collection_select :list_ids, List.where(user_id: current_user), :id, :name, {}, {multiple: true, required: true} %>

答案 1 :(得分:1)

试试这个

<%= f.collection_select(:list_ids, List.where(user_id: current_user), :id, :name, {}, {multiple: true, required: true}) %>

说明:

根据Rails文档,collection_select函数的语法如下所示:

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

根据语法选项和html_options是哈希值,因此您需要将它们括在大括号中。

参考 - http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

Credit

答案 2 :(得分:0)

<%= form.collection_select :msr_cd, 
    @msrs, :msr_cd, :msr_cd,
      {multiple: false, required: true},
      data: { placeholder: "Select Measure" }, 
      class: "form-control col-sm-12 chosen-select"  
%>

Note:
    @msrs from the controller
    :msr_cd - option value`enter code here`
    :msr_cd - option text

We can pass the chosen select like above