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?

5 Answers 5

227

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|
1
  • 1
    I found that this doesn't work: = form_for @user, :html => {'class' => 'x'} do |f|. class should be a symbol instead of string. Dec 17, 2015 at 4: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? %>
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).

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

0
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

4
  • 3
    Wow, really? those should be exactly equivalent. You can reproduce this? Which version of Ruby are you using?
    – Alan H.
    Oct 29, 2014 at 4: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, 2014 at 0:07
  • Those two lines are exactly identical. Guessing you forgot to save in between?
    – nathanvda
    Jan 29, 2015 at 14:05
  • I know, they should be. For me it just wasn't working though. Saving wasn't the issue.
    – doz87
    Jan 30, 2015 at 3:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.