method

collection_select

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
public

Return select and option tags for the given object and method using options_from_collection_for_select to generate the list of option tags.

4Notes

Customizing prompt

Towbie · Aug 26, 200811 thanks

The :prompt option not only accepts a boolean value. It can also be given a string to define another than the standard prompt 'Please select'. Referring to the example it could read:

collection_select(:post, :author_id, Author.find(:all),
                :id, :name_with_initial,
               {:prompt => 'Please select the author of this post'})

Make an action onchange

ishka · Oct 10, 20082 thanks
collection_select(nil, :provincia_id,  @provincias,  :id, :nombre, 
{:prompt   => "Seleccione una provincia"}, 
{:onchange => "#{remote_function(:url  => {:controller =>  'direccions', :action => "update_pueblos"}, 
:with => "'provincia_id='+value")}"})

:selected

nachocab · Jun 29, 20092 thanks

If you want some object to be selected by default, be sure to use its id, not the whole object.

collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:selected => current_book.authors.map(&:id)}) #=> :selected => [1,2,3,4]

and not collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:selected => current_book.authors})

Post =form post, NOT the http POST method

annaswims · Mar 17, 2009

Post =forum post, NOT the http POST method

Note: any "Post" on this page has nothing to do with http methods. When I just looked at the collection_select code I was thrown off.