【问题标题】:How do I set the HTML options for collection_select in Rails?如何在 Rails 中为 collection_select 设置 HTML 选项?
【发布时间】:2010-12-29 04:30:56
【问题描述】:

我似乎找不到将类添加到由 Rails collection_select 生成的选择标记的语法。有什么帮助吗?

【问题讨论】:

  • 你能举一些你想做的例子吗?我不明白你的问题。
  • 当然...我正在使用 rails 的 来生成: 我只是想要它是:

标签: html ruby-on-rails drop-down-menu


【解决方案1】:

许多 Rails 助手采用多个哈希参数。第一个通常是控制助手本身的选项,第二个是您指定自定义 id、类等的 html_options。

方法定义如下:

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

您会注意到参数列表中有多个“= {}”。要使用它,您要指定的第一组选项实际上必须用大括号括起来:

collection_select(:user, :title, UserTitle.all, :id, :name, {:prompt=>true}, {:class=>'my-custom-class'})

如果除了 html 类之外没有任何选项可以指定,那么只需放置一个空的 hash 占位符:

collection_select(:user, :title, UserTitle.all, :id, :name, {}, {:class=>'my-custom-class'})

其他 API 文档位于: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

【讨论】:

  • 这里是这个答案的扩展,展示了如何修改 .css 样式和使用 jQuery onchange 事件<%= collection_select(:question , :text, Question.all , :id, :text, {:prompt => 'Select Question...'}, {:class=>'input', :name=>'normalSelect', :id=>'normalSelect', :style=>'width:50%', :onchange=>"$('#accordion').accordion('activate',2);$('#blind').show('blind', 500)"}) %>
【解决方案2】:
= f.collection_select :category_id, Category.order(:name), :id, :name, {}, {class: "store-select"}

【讨论】:

    【解决方案3】:

    以防万一,我正在为同样的问题苦苦挣扎,我分享了我的结果,我只是尝试输入{},{},所以我必须更明确地输入:options = {}, html_options = {},因为它不适用于我。

    <div class="field">
       <%= form.label :country_id %>
       <%= form.collection_select :country_id, @countries,:id, :name, options = {:prompt => 'Select a Country...'},
            html_options = {class: "dropdown"}%>
     </div>
    

    问候!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      相关资源
      最近更新 更多