如何在 Rails 中为 collection_select 设置 HTML 选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1947578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:39:27  来源:igfitidea点击:

How do I set the HTML options for collection_select in Rails?

htmlruby-on-railsdrop-down-menu

提问by tybro0103

I can't seem to find the syntax to add a class to a select tag generated by Rails collection_select. Some help?

我似乎找不到将类添加到由 Rails 生成的 select 标记的语法collection_select。一些帮助?

回答by Drew Blas

Many Rails helpers take multiple hash arguments. The first is usually the options to control the helper itself, and the second is the html_options where you specifiy custom ids, classes etc.

许多 Rails 助手接受多个散列参数。第一个通常是控制帮助程序本身的选项,第二个是 html_options,您可以在其中指定自定义 id、类等。

The method definition looks like this:

方法定义如下所示:

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

You'll notice the multiple '= {}' in the params list. To use this, the first set of options that you would specify must actually be enclosed in braces:

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

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

If you don't have any options to specify besides the html class, then just put an empty hash placeholder:

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

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

Additional API documentation is available at: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

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

回答by drjorgepolanco

= f.collection_select :category_id, Category.order(:name), :id, :name, {}, {class: "store-select"}