Include blank for first item in select list in options_for_select tag

Viewed 88315

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

<select>
    <%= options_for_select Model.all.collect{|mt| [mt.name, mt.id]} %>
</select>

If I need to add it to the collection, how would you do that?

7 Answers
= 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])

You can use the following monkey patch to add the include_blank argument to options_for_select

module OptionsForSelectIncludeBlankPatch

  def options_for_select(container, selected = nil)
    if selected.is_a?(Hash)
      include_blank = selected[:include_blank] || selected['include_blank']
    end

    options = super

    if include_blank
      include_blank = '' if include_blank == true

      if Rails::VERSION::MAJOR >= 5 && Rails::VERSION::MINOR >= 1
        str = tag_builder.content_tag_string(:option, include_blank, {value: ''})
      else
        str = content_tag_string(:option, include_blank, {value: ''})
      end

      options.prepend(str)
    end

    options
  end

end

ActiveSupport.on_load(:action_view) do
  ActionView::Base.send(:include, RearmedRails::RailsHelpers)
end
Related