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

这一生的挚爱 提交于 2020-01-20 12:27:51

问题


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?


回答1:


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|



回答2:


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



回答3:


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




回答4:


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




回答5:


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



来源:https://stackoverflow.com/questions/13144624/use-rails-form-for-but-set-custom-classes-attributes-on-form-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!