Adding classes to fields in customized Rails form templates

I'm trying to create a template to my Rails app forms using this recipe here, i.e., customizing the file lib/templates/erb/scaffold/_form.html.erb.

All I want is to make all the inputs with type="text" to have the same class="form-control", because I'm using Bootstrap 3.

Now, all these inputs are generated by this line in the template:

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

My problems are:

  1. I didn't understand completely the syntax of this line, what it is exactly saying, then it is hard to modify it according to my needs; and,
  2. I tried to substitute this line for other options, but none worked and I always get runtime errors.

May someone help me with some clue about what to do? Or at least explain me the syntax of the line generating these inputs now, so I can continue myself?

Thanks in advance!

Upvotes: 0

Views: 354

Answers (1)

Fabiano Arruda
Fabiano Arruda

Reputation: 648

Explaining what is happening here:

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

The first method field_type of a generated attribute is basically getting the field type that rails needs to generate for this field. Looking at the method implementation you will find what it does:

# 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

The same goes for the second method 'column_name', It is quite self explanatory by looking at the source:

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

If you wonder what the <%% stands for: It is escaping ERB code, so it will result a single <% in final generated template.

Now, to achieve what you want, do like this:

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

Upvotes: 2

Related Questions