将类添加到自定义Rails表单模板中的字段

时间:2016-03-11 13:39:16

标签: ruby-on-rails twitter-bootstrap

我正在尝试使用此配方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. 我试图用这行替换其他选项,但没有一个工作,我总是遇到运行时错误。
  3. 有人可以帮我解决一下该做些什么吗?或者至少向我解释现在生成这些输入的行的语法,所以我可以继续自己吗?

    提前致谢!

1 个答案:

答案 0 :(得分:2)

解释这里发生的事情:

<%%= 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

如果你想知道<%%代表什么:它正在逃避ERB代码,因此它将在最终生成的模板中产生一个<%

现在,为了实现你想要的,做到这样:

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