instance method collection_select

Ruby on Rails 3.0.20

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

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

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.

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>

Parameters

object req
method req
collection req
value_method req
text_method req
options opt = {}
html_options opt = {}
Source
# File actionpack/lib/action_view/helpers/form_options_helper.rb, line 165
      def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
        InstanceTag.new(object, method, self, options.delete(:object)).to_collection_select_tag(collection, value_method, text_method, options, html_options)
      end

Defined in actionpack/lib/action_view/helpers/form_options_helper.rb line 165 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::FormOptionsHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close