Rails and Bootstrap

This hit me when I was rewriting front-end part of Zeropaste. Of course later I found out that there’s gem for it.

But anyway, if you don’t want to add another gem and feel like writing crapload of divs, it’s not that difficult. It breaks Rails standard form error handling though.

First, change the default error field handling to do nothing instead of wrapping it in a div:

config.action_view.field_error_proc = proc { |html| html }

(put in application.rb)

And then create this helper:

def error_class(object, attribute)
  "has-error" if object.errors.include? attribute
end

Finally, here’s how to use it (for attribute key of a model):

<div class="form-group <%= error_class f.object, :key %>">
  <%= f.label :key %>
  <%= f.text_field :key, :class => "form-control" %>
</div>

…and done.