Use Rails’ form_for but set custom classes, attributes on <form> element?

Ruby on-RailsRuby on-Rails-3

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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|

Solution 2 - Ruby on-Rails

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? %>

Solution 3 - Ruby on-Rails

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).

Solution 4 - Ruby on-Rails

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

Solution 5 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlan H.View Question on Stackoverflow
Solution 1 - Ruby on-RailsMurifoXView Answer on Stackoverflow
Solution 2 - Ruby on-Railszero_coolView Answer on Stackoverflow
Solution 3 - Ruby on-RailsMSCView Answer on Stackoverflow
Solution 4 - Ruby on-RailsfelipeclopesView Answer on Stackoverflow
Solution 5 - Ruby on-Railsdoz87View Answer on Stackoverflow