Collection_select with array as source


#1

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

I would be grateful for any help.
Thanks,
Shelby


#2

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) + “”
when Hash
arg["-- make a selection --"] = ‘0’
select_name + options_for_select(arg.sort, selected) +
“”
end
end


#3

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”} %>