109

form_for seems to ignore any 'extra' attributes like a data-foo attribute or class passed as options in its second argument.

= form_for @user, {:url => 'foo', :class => 'x', 'data-bar' => 'baz' } do |f|
  # ...

The output is a <form> tag with no x class or data-bar attribute.

What’s the fix?

Or, how can I grab a FormBuilder instance without using form_for?

Alan H.
  • 16,219
  • 17
  • 80
  • 113

5 Answers5

225

Use the :html hash:

= form_for @user, :html => {:class => 'x', 'data-bar' => 'baz'} do |f|

Or

= form_for @user, html: {class: 'x', data: { bar: 'baz' } } do |f|
Alan H.
  • 16,219
  • 17
  • 80
  • 113
MurifoX
  • 14,991
  • 3
  • 36
  • 60
  • 1
    I found that this doesn't work: `= form_for @user, :html => {'class' => 'x'} do |f|`. `class` should be a symbol instead of string. – Trantor Liu Dec 17 '15 at 04:54
11

Rails 4.0.3, Ruby 2.1.0p0 -> this worked for me =>

<%= form_for(@contact, :html => {:class => 'form_height'}) do |f| %><% if     @contact.errors.any? %>
zero_cool
  • 3,960
  • 5
  • 39
  • 54
5

I had the same problem but was puzzled that another form elsewhere in my app was working fine.

I realized that I had accidentally added a form_for inside another form_for which once removed cured the problem.

Secondly, I should add that this syntax works for me in Rails 4.2:

<%= form_for @type, html: {class: "form-horizontal"} do |f| %>

I find it preferable to the punctuation-soup of the other answers here (which were perhaps based on an older Rails version).

MSC
  • 3,286
  • 5
  • 29
  • 47
1

On mostly helpers, the last arg is a hash of html options for the element.

= form_for @user, :html => {:class => 'x', 'data-bar' => 'baz'} %>

You can also check other alternatives in the documentation ActionsView::Helpers::FormHelper

felipeclopes
  • 4,010
  • 2
  • 25
  • 35
1

I tried the above with no luck but found a solution. I'm using rails 4.1.6.

This didn't work

= form_for @user, :html => {:class => 'x', 'data-bar' => 'baz'} %>

This did

= form_for @user, html: {:class => 'x', 'data-bar' => 'baz'} %>

notice the difference with the html option, hope this helps

doz87
  • 591
  • 6
  • 15
  • 3
    Wow, really? those should be exactly equivalent. You can reproduce this? Which version of Ruby are you using? – Alan H. Oct 29 '14 at 04:01
  • @Alan H. Using Ruby 2.1.3p242 `= form_for(:user, :url => login_path, html: {:class => 'login_form'}) do |f| %>` This was the only way that my code would apply the class, otherwise it was just ignoring it. – doz87 Oct 30 '14 at 00:07
  • Those two lines are exactly identical. Guessing you forgot to save in between? – nathanvda Jan 29 '15 at 14:05
  • I know, they should be. For me it just wasn't working though. Saving wasn't the issue. – doz87 Jan 30 '15 at 03:50