How to add a css class to start_form_tag in Ruby on Rails
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 is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.
Contact
my name at gmail.com
More snippets
Take a look in the archive
Need a website?
Contact my employer. Make sure to check out our portfolio of work.
Hosting
I recommend hostingrails.com
4 comments made
Thanks a lot. Looked for that info for an hour and could not manage until I found this post. All the best.
Thanks, this was exactly what I needed! Excellent website!
There’s a blog entry at
http://www.tortoiseandachilles.com/2007/08/ruby-of-rails-named-parameter-passing.html 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.
Thanks for the help! I spent close to an hour trying different things and trying to work it out. Best of Luck to you.
Got something to say?