Forum: Ruby on Rails collection_select with array as source

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Shelby W. (Guest)
on 2006-01-04 19:41
(Received via mailing list)
I would like to use the collection_select with a simply array as the
of the collection.

My array looks like this:
STATES = ["Alabama", "Alaska", "Texas"]
and it is stored in my environment.rb

I can't figure out the syntax for the collection_select in this

collection_select("my_object", "state", what goes here??? )

I just need the state name to go on both the value and the label field
each <option>

I would be grateful for any help.
Steve R. (Guest)
on 2006-01-04 21:23
Consider putting something like this in either application_helper.rb or
one of your specific controllers. I believe the code can be improved a
bit by replaicing the escaped strings with %() delimiters.

Note that I add "make a selection" to the top of my drop-downs and sort

Hope this helps.

    def select_from_hash(object, name, arg, selected = nil)
        raise "list of '#{name}' is nil" if arg.nil?
        select_name = "<select name=\"#{object}[#{name}]\"
        case arg
        when Array
          arg.unshift('-- make a selection --')
          select_name + options_for_select(arg.sort{|k,v| k[1] <=>
v[1]}, selected) + "</select>"
        when Hash
          arg["-- make a selection --"] = '0'
          select_name + options_for_select(arg.sort, selected) +
Kevin O. (Guest)
on 2006-01-04 21:31
Shelby W. wrote:

> My array looks like this:
> STATES = ["Alabama", "Alaska", "Texas"]
> and it is stored in my environment.rb

try this...

<%= select "my_object","state", STATES, {:prompt=>"Select State"} %>
This topic is locked and can not be replied to.