Forum: Ruby on Rails collection_select with array as source

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.
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
source
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
situation...

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

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

I would be grateful for any help.
Thanks,
Shelby
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
alphabetically.

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}]\"
id=\"#{object}[#{name}]\">".freeze
        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) +
"</select>"
        end
    end
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.