how to create select box from a given list in rails?

て烟熏妆下的殇ゞ 提交于 2019-12-24 20:15:07

问题


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"



来源:https://stackoverflow.com/questions/17229947/how-to-create-select-box-from-a-given-list-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!