Ruby-on-rails 如何在rails中使用form_tag设置类属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9090994/
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
how to set class attribute with form_tag in rails
提问by John
I have the following line of haml:
我有以下haml行:
=form_tag :action => 'create', :controller => 'comments', :class => 'comment_form' do
But the html that gets output is:
但是得到输出的html是:
<form accept-charset="UTF-8" action="/comments?class=comment_form" method="post"></form>
I want to set the class. How do I do this?
我想设置类。我该怎么做呢?
<-- Update -->
<-- 更新-->
With this:
有了这个:
=form_tag ({ :action => 'create', :controller => 'comments' }, { :class => 'comment_form' }) do
I get this error:
我收到此错误:
syntax error, unexpected ',', expecting ')'
...', :controller => 'comments' }, { :class => 'comment_form' }...
<-- Second Update -->
<-- 第二次更新-->
The problem above is the space between 'form_tag' and '(' @woahdae's answer is correct
上面的问题是'form_tag'和'('之间的空格@woahdae的答案是正确的
回答by Woahdae
form_tagtakes 2 options hashes, the first being passed to url_for, the second being passed to the form builder.
form_tag接受 2 个选项哈希,第一个传递给url_for,第二个传递给表单构建器。
So, you have to do it like:
所以,你必须这样做:
= form_tag({:action => 'create',...}, {:class => 'comment_form'}) do
otherwise Rails thinks all the key/value pairs are for url_for, which will append any keys it doesn't understand as query parameters.
否则 Rails 认为所有的键/值对都是针对 url_for 的,它将附加任何它不理解的键作为查询参数。
回答by gamov
This works for me:
这对我有用:
form_tag named_route, :method => :put, :class => 'disable_on_submit'
With Rails 3.0.15
使用 Rails 3.0.15
回答by pastullo
On Rails 5, you can do the following:
在 Rails 5 上,您可以执行以下操作:
<%= form_tag(your_named_path, {class: 'form-inline'}) do %>
<% end %>
回答by Khanh Pham
You can do follow as:
您可以按照以下方式操作:
form_tag your_path, method: :get, id: "your_id", class: "your_class" do
end
回答by Fellow Stranger
In case you found this question and actually wanted to solve class naming for a form_for:
如果您发现了这个问题并且实际上想解决form_for 的类命名问题:
<%= form_for @task, html: {:class => "custom_class"} do |f| %>

