method

collection_select

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

Returns <select> and <option> tags for the collection of existing return values of method for object's class. The value returned from calling method on the instance object will be selected. If calling method returns nil, no selection is made without including :prompt or :include_blank in the options hash.

The :value_method and :text_method parameters are methods to be called on each member of collection. The return values are used as the value attribute and contents of each <option> tag, respectively. They can also be any object that responds to call, such as a proc, that will be called for each member of the collection to retrieve the value/text.

Example object structure for use with this method:

class Post < ActiveRecord::Base
  belongs_to :author
end

class Author < ActiveRecord::Base
  has_many :posts
  def name_with_initial
    "#{first_name.first}. #{last_name}"
  end
end

Sample usage (selecting the associated Author for an instance of Post, @post):

collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)

If @post.author_id is already 1, this would return:

<select name="post[author_id]">
  <option value="">Please select</option>
  <option value="1" selected="selected">D. Heinemeier Hansson</option>
  <option value="2">D. Thomas</option>
  <option value="3">M. Clark</option>
</select>

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.