How to set an empty value for a form field f.select

I use the following so that my users can select their gender in their profile.

<%= f.select (:sex, %w{ Male Female }) %> 

How do I create an empty value that the list will have by default if nothing was passed to the user.sex column? I just walk past a man or a female.

Purpose: I want an empty value, so checking can make sure they know they need to select it.

+53
ruby select ruby-on-rails
Dec 14 '10 at 21:40
source share
5 answers

Depending on what you are after: there are two possibilities:

include_blank

 <%= f.select (:sex, %w{ Male Female }, :include_blank => true) %> 

This will always include an empty parameter in select, which will allow people to return the value to an empty value if they see it in the edit form.

prompt

 <%= f.select (:sex, %w{ Male Female }, :prompt => "Gender...") %> 

This will include the specified prompt value if the field is not already set. If he has (for example, in the editing form), there is no need to remind the user that they need to select a value so that the invitation does not appear

+119
Dec 14 '10 at 21:44
source share
— -

I think you can do something like this:

 <%= f.select (:sex, %w{ Male Female }, {:include_blank => 'None Specified'} ) %> 
+32
Dec 14 '10 at 21:45
source share

in Rails 4 you can do this:

 <%= f.select :gender, %w{ Male Female }, {:prompt => "Gender..."} %> 

it works for me with a simple form.

+3
Feb 06 '15 at 16:10
source share

You go with

 <%= f.select :gender, %w{ Male Female }, :include_blank => true %> 
0
Feb 06 '15 at 18:16
source share

I tried to use the "prompt" as a string. But in the displayed output, a prompt for a new option did not appear. The select_tag method searches only for a character. This seems to apply to: include_blank. Check options.delete:

  def select_tag(name, option_tags = nil, options = {}) option_tags ||= "" html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name if options.include?(:include_blank) include_blank = options.delete(:include_blank) if include_blank == true include_blank = '' end if include_blank option_tags = content_tag(:option, include_blank, value: '').safe_concat(option_tags) end end if prompt = options.delete(:prompt) option_tags = content_tag(:option, prompt, value: '').safe_concat(option_tags) end content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys) end 

Also note that: include_blank and: prompt will be select or select_tag parameters, not options_for_select.

0
May 20 '19 at 22:53
source share



All Articles