Include blank for first item in select list in options_for_select tag

前端 未结 6 2063
南方客
南方客 2020-12-08 18:26

I tried :include_blank => true, but it didn\'t work.


                        
    
提交评论

  • 2020-12-08 18:55

    I think you want this format:

    select("model_name", "model_id", Model.all.collect {|mt| [ mt.name, mt.id ] }, {:include_blank => 'name of your blank prompt'})
    

    BTW: was assuming Modle was suppose to be Model. To use using collection_select:

    collection_select(:model, :model_id, Model.all, :id, :name, :prompt => true)
    
    0 讨论(0)
  • 2020-12-08 18:56
    = select_tag "some_value", options_for_select(Model.all.collect{ |x| [x.name, x.id]}.prepend([t('helpers.some_name'), nil]), :selected => params[:some_value])
    
    0 讨论(0)
  • 2020-12-08 18:58

    Since you have tagged as select-tag you can use the option include_blank with select_tag.

    From the documentation:

    select_tag "people", options_from_collection_for_select(@people, "id", "name"), :include_blank => true
    
    # => <select id="people" name="people"><option value=""></option><option value="1">David</option></select>
    

    Or you can use options_for_select:

    <%= select_tag column.name, options_for_select(Model.all.collect{|mt| [mt.name, mt.id]}), :include_blank => true %>
    
    0 讨论(0)
  • 2020-12-08 19:00
    <%= options_for_select Model.all.collect{|x| [x.name,x.id]}.unshift(["",nil]) %>
    
    0 讨论(0)
  • 2020-12-08 19:01

    If you want a slick solution you can use my gem rearmed_rails which has a feature in it that safely monkey patches options_for_select and options_for_collection_select

    rails g rearmed_rails:setup

    Open config/initializers/rearmed_rails.rb and change the following values to true

    options_for_select_include_blank: true,
    options_from_collection_for_select_include_blank: true
    


    Now whenever you need a blank included simply do the following:

    <%= options_for_select(Model.all.map{|x| [x.name,x.id]}, include_blank: true) %>
    
    0 讨论(0)
  • 自定义标题
    段落格式
    字体
    字号
    代码语言
    提交回复
    热议问题