Forum: Ruby on Rails Default option in collection_select

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Yehuda K. (Guest)
on 2006-03-12 02:33
I need a way to set a default in a collection_select. Any way?
Roland (Guest)
on 2006-03-12 02:56
I use:

options_for_select(container, selected = nil)

Hope it helps...
Rath -. (Guest)
on 2006-03-12 03:40
You can create a helper like this one using options_for_select

def my_select(object, method, choices, options = {})
  html = ""
  if options[:id]
    html << "<select name='#{object}[#{method}]' id='#{options[:id]}'>"
  else
    html << "<select name='#{object}[#{method}]'
id='#{object}_#{method}'>"
  end
  html << options_for_select(choices, options[:selected])
  html << "</select>"
  html
end

And call it from the view
<%= my_select 'telephone', 'type', @telephone_types, :selected =>
'Mobile' %>

Or if you want a blank option at the top (or display any text) you can
use the :prompt option.

<%= select('telephone', 'type', @telephone_types, {:prompt => "Select
Type"}) %>

Hope this helps

Rafa
This topic is locked and can not be replied to.