Ruby on Rails form_for 选择带有类的字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4081907/
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
Ruby on Rails form_for select field with class
提问by Patrick
I am beating my head against the wall on this one. I want to make a simple select tag using the f.selecttag but nothing I do works. I put an example below:
我正在用头撞墙。我想使用f.select标签制作一个简单的选择标签,但我所做的一切都不起作用。我在下面举了一个例子:
<%= f.select(:object_field, ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 4'], :class => 'my_style_class')%>
Ok, so basically it is a simple list that once the form is submitted it places the value into the object_field. That all works, but viewing the page source the class tag is not included. It doesn't throw an error, it just skips it all together.
好的,所以基本上它是一个简单的列表,一旦提交表单,它就会将值放入object_field. 一切正常,但查看页面源时不包含 class 标记。它不会抛出错误,它只是一起跳过它。
If anyone has any suggestions I would greatly appreciate it.
如果有人有任何建议,我将不胜感激。
回答by MBO
Try this way:
试试这个方法:
<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>
selecthelper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options.
selecthelper 需要两个选项哈希,一个用于选择,第二个用于 html 选项。因此,您只需要在项目列表之后提供默认的空选项作为第一个参数,然后将您的类添加到html_options.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select
回答by Paing Soe Thaw
You can also add prompt option like this.
您还可以添加这样的提示选项。
<%= f.select(:object_field, ['Item 1', 'Item 2'], {include_blank: "Select something"}, { :class => 'my_style_class' }) %>
回答by Alex Onozor
This work for me
这对我有用
<%= f.select :status, [["Single", "single"], ["Married", "married"], ["Engaged", "engaged"], ["In a Relationship", "relationship"]], {}, {class: "form-control"} %>
回答by ThienSuBS
You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select
你可以在这里看到:http: //apidock.com/rails/ActionView/Helpers/FormBuilder/select
Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select
或在这里:http: //apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select
Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.
Select 标签最多有 4 个参数,最后一个参数是 html 选项,这意味着你可以在这里放 class、require、selection 选项。
= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}

