HAML and Rails View Helpers

I hit another little snag last night with HAML.  Take a look at this page:

formYou can see that the bootstrap formatting on the second form input is wrong and the page is rendering a default html form.  The first form is working right.  Here’s the HAML:

form code

The correct code is on lines 8 and 9.  The incorrect code is on lines 11 and 12. This is something that is obvious once you understand it, but not so obvious at first.  With HAML, you can create a class for a div by typing

.className

So it seems like if you want to create a text box input, you could just type

.form-control

But what this actually does is create a div with the class “form-control”:

incorrect html

The input is created without a class within that div. Thus, a plain html input box.

form_for, .label,  and other rails view helpers are Ruby code that generate HTML. So you have to prefix them like so, with the class declaration within the attributes hash:

=f.text_field :first_name, class: "form-control"

Like I said, obvious once you understand it. But it took me a while to figure out.

Leave a Reply

Your email address will not be published. Required fields are marked *