RoR - Select tag with include_blank disable

后端 未结 4 1715
无人共我
无人共我 2021-01-12 04:14

I want a result like this :


                        
    
提交评论

  • 2021-01-12 04:50

    I believe they add the functionality in Rails 6.

    From the pull request:

    Enable select tag helper to mark prompt option as selected and/or disabled for required field. Example:

    select :post, 
           :category, 
           ["lifestyle", "programming", "spiritual"], 
           { selected: "", disabled: "", prompt: "Choose one" }, 
           { required: true }
    

    Placeholder option would be selected and disabled. The HTML produced:

    <select required="required" name="post[category]" id="post_category">
      <option disabled="disabled" selected="selected" value="">Choose one</option>
      <option value="lifestyle">lifestyle</option>
      <option value="programming">programming</option>
      <option value="spiritual">spiritual</option>
    </select>
    
    0 讨论(0)
  • 2021-01-12 04:52

    I believe what you are looking for is as below:

    <%= f.select(:car, xxxxxx, {:include_blank => 'Choose a car', :disabled => 1}) %>
    
    0 讨论(0)
  • 2021-01-12 05:02

    An application of the above noted solution follows.

    create the application helper function

    def build_selections(prompt: "Select One", selections: {})
        selections.reverse!.push([prompt, nil]).reverse! 
    end
    

    then use it in your view:

    <%= f.select :category_id, build_selections(prompt: 'Select Category',
                               selections: @category.collect{|x| [x.name, x.id]}),
                               disabled: '' %>
    
    0 讨论(0)
  • 提交回复
    热议问题