how to create select box from a given list in rail

2019-08-16 02:51发布

问题:

I am passing a list from my controller

 @distinct_grade_list = Student.uniq.pluck(:grade)

which creates the distinct list of grades from model Student

now in my view page , how can i display it as select box I am using

<%= collection_select(A, @distinct_grade_list, B, C, D) %>

now what do i have to keep at A,B,C,D

回答1:

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

why not read the api document and sample?

sample usage:

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)

and result:

<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>

The value returned from calling method on the instance object will be selected

call :author_id on :post, @post is you passed from controller

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 tag, respectively.

:id is value_method :name_with_initial is text_method collection is used to populated "options"