What is the correct button_to syntax for adding a class to the generated form?

digitalWestie picture digitalWestie · Feb 15, 2012 · Viewed 16.3k times · Source

I'm trying to apply a class to the form generated by button_to in Rails 3.

The :class option sets the class for the submit button so the docs tell us to use :form_class to apply a class to the form.

E.g.

<%= button_to 'x', user_contact_path(@user, contact), :method => :delete, :form_class => "delete" %>

This just adds the attribute form_class="delete" to the button element. I've tried various combinations using :html_options and so on.

Anybody know how to do this?

Answer

Syed Aslam picture Syed Aslam · Feb 15, 2012

That method works perfectly fine for me. I am able to do:

<%= button_to "Hello", root_url, :method => :get, :form_class => "my_class" %>

the above generates the following:

<form action="http://localhost:3000/" class="my_class" method="get">
  <div><input type="submit" value="Hello"></div>
</form>

However, this is in Rails 3.1 as the link in your question points and the same wouldn't work in Rails 3.0.x since the form class is hard coded.

From url_helper code:

("<form method=\"#{form_method}\" action=\"#{html_escape(url)}\" 
  #{"data-remote=\"true\"" if remote} class=\"button_to\"><div>" +
  method_tag + tag("input", html_options) + request_token_tag + 
  "</div></form>"
).html_safe