How to add a css class to start_form_tag in Ruby on Rails

Posted on 07 April 2006

To add a class to a form in Ruby on Rails using start_form_tag isn't immediately obvious. I achieved it like this:


<%= start_form_tag( {}, {:class => 'classnamehere'}) %>

The empty curly brackets are where you might enter the controller or action.

The key part to the start_form_tag helper though, are the brackets ( ) which aren't necessary for many other helpers, this is an odd inconsistency in Rails that I have found.

Incidently start_form_tag is an alias for form_tag so it does exactly the same thing.

The following is taken from the Rails API that helped me figure this out.


def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &proc)
  html_options = { "method" => "post" }.merge(options.stringify_keys)
  html_options["enctype"] = "multipart/form-data" if      html_options.delete("multipart")
  html_options["action"] = url_for(url_for_options, *parameters_for_url)
  tag :form, html_options, true
end

Update 24/05/07

Note that start_form_tag is now deprecated and that in Rails 2.0 you will need to switch to the following:

<% form_tag({:action => "foo"},{:class => "bar"}) do %>
  insert code
<% end %>

About Paul

Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.

Follow Paul on Twitter

Email: paulsturgess [at] gmail.com

Read more articles in the archive →

Comments...

  • Thanks a lot. Looked for that info for an hour and could not manage until I found this post. All the best.

    Swami Atma at 23 May 07 at 20:32

  • Thanks, this was exactly what I needed! Excellent website!

    Scott W. at 26 May 07 at 01:30

  • There's a blog entry at

    <a href="http://www.tortoiseandachilles.com/2007/08/ruby-of-rails-named-parameter-passing.html">http://www.tortoiseandachilles.com/2007/08/ruby-of-rails-named-parameter-passing.html</a> that explains why you need the parentheses (). It's not really an inconsistency, once you see the logic.

    My name above this comment links to the blog entry, although I didn't write it.

    Jimmy at 14 Aug 07 at 17:44

  • Thanks for the help! I spent close to an hour trying different things and trying to work it out. Best of Luck to you.

    Mario at 07 Oct 07 at 22:01

  • Awesome! Thanks for that

    Chris at 23 Jan 09 at 02:39

  • Thanks for the useful information.

    prasad at 26 Aug 09 at 04:37

  • () are parentheses, [] are brackets -- a minor quibble in grammar, perhaps, but they are rarely interchangable in tech, so it's good to keep the lingo straight.

    ec at 02 Jun 10 at 18:27

  • Thanks.

    Giovanni at 03 Feb 12 at 13:15

Got something to say?