【问题标题】:Adding classes to fields in customized Rails form templates向自定义 Rails 表单模板中的字段添加类
【发布时间】:2016-03-11 13:39:15
【问题描述】:

我正在尝试使用此配方 here 为我的 Rails 应用程序表单创建一个模板,即自定义文件 lib/templates/erb/scaffold/_form.html.erb

我只想让 type="text" 的所有输入都具有相同的 class="form-control",因为我使用的是 Bootstrap 3。

现在,所有这些输入都是由模板中的这一行生成的:

<%%= f.<%= attribute.field_type %> :<%= attribute.column_name %> %>

我的问题是:

  1. 我没有完全理解这行的语法,它到底在说什么,然后很难根据我的需要修改它;并且,
  2. 我尝试将此行替换为其他选项,但没有一个有效,并且我总是遇到运行时错误。

有人可以帮我提供一些关于该怎么做的线索吗?或者至少现在解释一下生成这些输入的行的语法,这样我就可以继续自己了?

提前致谢!

【问题讨论】:

    标签: ruby-on-rails twitter-bootstrap


    【解决方案1】:

    解释这里发生了什么:

    <%%= f.<%= attribute.field_type %> :<%= attribute.column_name %> %>
    

    生成属性的第一种方法field_type,基本上就是获取rails需要为这个字段生成的字段类型。查看method implementation 你会发现它的作用:

    # File railties/lib/rails/generators/generated_attribute.rb, line 66
      def field_type
        @field_type ||= case type
          when :integer              then :number_field
          when :float, :decimal      then :text_field
          when :time                 then :time_select
          when :datetime, :timestamp then :datetime_select
          when :date                 then :date_select
          when :text                 then :text_area
          when :boolean              then :check_box
          else
            :text_field
        end
      end
    

    第二个方法“column_name”也是如此,通过查看source,这很容易解释:

    # File railties/lib/rails/generators/generated_attribute.rb, line 116
      def column_name
        @column_name ||= reference? ? "#{name}_id" : name
      end
    

    如果您想知道 &lt;%% 代表什么:它正在转义 ERB 代码,因此它会在最终生成的模板中生成一个 &lt;%

    现在,要实现您想要的,请这样做:

    <%%= f.<%= attribute.field_type %> :<%= attribute.column_name %>, class: '<%= attribute.field_type %> form-control' %>
    

    【讨论】:

    • 谢谢!但我仍然在 中遇到错误。它说“未找到变量或方法”。
    • 对不起,我的错。 column.field_type 应该是 attribute.field_type。我更正了原来的答案。
    • 我应该补充一点,类声明的第一部分是可选的。它只会添加一个名为属性类型的类,以防您想基于它添加特定的 css 样式。但为了简单起见,您可以直接使用:&lt;%%= f.&lt;%= attribute.field_type %&gt; :&lt;%= attribute.column_name %&gt;, class: 'form-control' %&gt;
    • 看来在接下来的几天里我会充满涉及neo4j和Rails的问题:stackoverflow.com/questions/35947181/…
    猜你喜欢
    • 2022-01-06
    • 2013-12-30
    • 2017-08-08
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多