Ruby-on-rails 使用 Rails 的 form_for 但在 <form> 元素上设置自定义类和属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13144624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:56:48  来源:igfitidea点击:

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

ruby-on-railsruby-on-rails-3

提问by Alan H.

form_forseems to ignore any 'extra' attributes like a data-fooattribute or classpassed as optionsin its second argument.

form_for似乎忽略任何“额外”属性,如data-foo属性或在其第二个参数中class传递options

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

The output is a <form>tag with no xclass or data-barattribute.

输出是一个<form>没有x类或data-bar属性的标签。

What's the fix?

有什么解决办法?

Or, how can I grab a FormBuilderinstance without using form_for?

或者,如何在FormBuilder不使用的情况下获取实例form_for

回答by MurifoX

Use the :htmlhash:

使用:html哈希:

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

Or

或者

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

回答by zero_cool

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

Rails 4.0.3,Ruby 2.1.0p0 -> 这对我有用 =>

<%= form_for(@contact, :html => {:class => 'form_height'}) do |f| %><% if     @contact.errors.any? %>

回答by MSC

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_forinside another form_forwhich once removed cured the problem.

我意识到,我不小心加了的form_for另一个内部的form_for曾经除去固化的问题。

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

其次,我应该补充一点,这个语法在 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).

我发现它比这里其他答案的标点符号汤更可取(它们可能基于较旧的 Rails 版本)。

回答by doz87

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

我没有运气就尝试了上述方法,但找到了解决方案。我正在使用导轨 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

注意与 html 选项的区别,希望这会有所帮助

回答by felipeclopes

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

在大多数助手上,最后一个 arg 是元素的 html 选项的散列。

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

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

您还可以在文档ActionsView::Helpers::FormHelper 中检查其他替代方案