如何在Ruby on Rails中向select_tag添加一个类

时间:2014-01-17 22:27:14

标签: css ruby-on-rails ruby twitter-bootstrap-3

难以在此处添加类标记:

 <div class="field">
    <%= label_tag(:school_or_org, "Are you a school or a non-profit organization?") %> 
    <%= select_tag(:school_or_org, options_for_select([ ['school', "school"], ['non-profit', "non-profit"] ]))  %> 
  </div>

这是我尝试过的,其中包括:

      <div class="field">
         <%= label_tag(:school_or_org, "Are you a school or a non-profit organization?") %> 
         <%= select_tag(:school_or_org, options_for_select([ ['school', "school"], ['non-profit', "non-profit"], {:class => 'form-control'} ]))  %> 
     </div> 

当我通过firefbug检查时,我没有看到课程信息,所以很明显它没有添加。

如何添加它以便显示在表单中?

的Merci

编辑一个

你的意思是这样的:

 <%= select_tag(:school_or_org, options_for_select([ ['school', "school"], ['non-profit', "non-profit"]] ), {:class => 'form-control'})  %> 

它不起作用。

仅供参考,我正在尝试让选择框看起来像:http://getbootstrap.com/css/#forms(查看选择部分)。这就是我从中获得“形式控制”的地方。

2 个答案:

答案 0 :(得分:15)

如果您使用the select helper,则需要一个空的选项哈希,然后是html选项,如下所示:

select(object, method, choices, options = {}, html_options = {})

使用您的示例,看起来像这样:

<%= select(:school_or_org, options_for_select([ ['school', "school"], ['non-profit', "non-profit"]] ), {}, {:class => 'form-control'})  %>

如果您使用的是the select_tag helper,则可以在末尾添加哈希作为选项哈希的一部分:

 select_tag(name, option_tags = nil, options = {})

这是有效的,因为任何未识别的选项都作为标准HTML属性传递。

使用您的示例,看起来像这样:

<%= select_tag(:school_or_org, options_for_select([ ['school', "school"], ['non-profit', "non-profit"]] ), {:class => 'form-control'})  %> 

答案 1 :(得分:2)

如果您想在选择框本身上使用该类,则此处会出现括号嵌套错误。 {:class => 'form-control'}代码段必须位于options_for_select调用的parens之外。

如果要将类应用于选项,则每个数组元素都需要类声明,如下所示:['non-profit', "non-profit", {:class => 'form-control'}]