如何从rails中的给定列表中创建选择框? [英] how to create select box from a given list in rails?

查看:30
本文介绍了如何从rails中的给定列表中创建选择框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从我的控制器传递一个列表

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

现在我必须在 A、B、C、D 保持什么

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

推荐答案

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

为什么不阅读 api 文档和示例?

示例用法:

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 是你从控制器传递过来的

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

:value_method 和:text_method 参数是要在集合的每个成员上调用的方法.返回值分别作为每个标签的值属性和内容.

:id 是 value_method:name_with_initial 是 text_method集合用于填充选项"

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

这篇关于如何从rails中的给定列表中创建选择框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆