collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {}) public
为什么不阅读api document and sample?
示例用法:
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
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, :prompt => true)
结果:
<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>
实例对象上调用方法返回的值会被选中
在 :post 上调用 :author_id,@post 是你从控制器传递过来的
:value_method 和:text_method 参数是要在集合的每个成员上调用的方法。返回值分别作为每个标签的值属性和内容。
:id 是 value_method
:name_with_initial 是 text_method
集合用于填充“选项”