【问题标题】:how to create select box from a given list in rails?如何从rails中的给定列表中创建选择框?
【发布时间】:2013-06-21 07:32:48
【问题描述】:

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

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

创建与模型学生不同的成绩列表

现在在我的视图页面中,我如何将其显示为选择框 我正在使用

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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2


    【解决方案1】:
    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 集合用于填充“选项”

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2023-04-08
    相关资源
    最近更新 更多