John
John

Reputation: 13705

how to set class attribute with form_tag in rails

I have the following line of haml:

=form_tag :action => 'create', :controller => 'comments', :class => 'comment_form' do

But the html that gets output is:

<form accept-charset="UTF-8" action="/comments?class=comment_form" method="post"></form>

I want to set the class. How do I do this?

<-- Update -->

With this:

=form_tag ({ :action => 'create', :controller => 'comments' }, { :class => 'comment_form' }) do

I get this error:

 syntax error, unexpected ',', expecting ')'
...', :controller => 'comments' }, { :class => 'comment_form' }...

<-- Second Update -->

The problem above is the space between 'form_tag' and '(' @woahdae's answer is correct

Upvotes: 35

Views: 41986

Answers (5)

Fellow Stranger
Fellow Stranger

Reputation: 34013

In case you found this question and actually wanted to solve class naming for a form_for:

<%= form_for @task, html: {:class => "custom_class"} do |f| %>

Upvotes: -2

pastullo
pastullo

Reputation: 4201

On Rails 5, you can do the following:

<%= form_tag(your_named_path, {class: 'form-inline'}) do %>

<% end %>

Upvotes: 8

Khanh Pham
Khanh Pham

Reputation: 2973

You can do follow as:

form_tag your_path, method: :get, id: "your_id", class: "your_class" do 
end

Upvotes: 1

Woahdae
Woahdae

Reputation: 5051

form_tag takes 2 options hashes, the first being passed to url_for, the second being passed to the form builder.

So, you have to do it like:

= form_tag({:action => 'create',...}, {:class => 'comment_form'}) do

otherwise Rails thinks all the key/value pairs are for url_for, which will append any keys it doesn't understand as query parameters.

Upvotes: 60

gamov
gamov

Reputation: 3859

This works for me:

form_tag named_route, :method => :put, :class => 'disable_on_submit'

With Rails 3.0.15

Upvotes: 8

Related Questions