【问题标题】:Required Field on collection_select type fieldcollection_select 类型字段上的必填字段
【发布时间】:2016-03-01 15:24:22
【问题描述】:

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

<%= 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 =&gt; true 选项,代码可以正常工作。在这种情况下,如何强制用户进行选择?谢谢

【问题讨论】:

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


【解决方案1】:

尝试更改此设置

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

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

    • 您的答案几乎是从SO post 中逐行复制的
    • 是的,你是对的,实际上我正准备将其标记为 dup
    【解决方案3】:
    <%= 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2014-06-25
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      相关资源
      最近更新 更多