Ruby-on-rails form_for 和 form_tag 的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1349348/
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
Difference between form_for , form_tag?
提问by devinross
What is the difference between form_for and form_tag? Is anything different for form_remote_for and form_remote_tag?
form_for 和 form_tag 有什么区别?form_remote_for 和 form_remote_tag 有什么不同吗?
采纳答案by ez.
You would use form_for for a specific model,
您可以将 form_for 用于特定模型,
<% form_for @person do |f| %> # you can use f here
First name: <%= f.text_field :first_name %>
Last name : <%= f.text_field :last_name %>
<% end %>
Form_tag create basic form,
Form_tag 创建基本表单,
<%= form_tag '/person' do -%>
<%= text_field_tag "person", "first_name" %>
<% end -%>
回答by giorgian
form_forprefers, as its first arg, an activerecord object; it allows to easily make a create or edit form (to use it in a "new" view you should create an empty instance in controller, like:
form_for更喜欢,作为它的第一个参数,一个 activerecord 对象;它允许轻松创建或编辑表单(要在“新”视图中使用它,您应该在控制器中创建一个空实例,例如:
def new
@foo = Foo.new
end
It also passes a form variable to the block, so that you don't have to repeat the model name within the form itself. it's the preferred way to write a model related form.
它还将表单变量传递给块,这样您就不必在表单本身内重复模型名称。这是编写模型相关表单的首选方式。
form_tagjust creates a form tag (and of course silently prepare an antiforgery hidden field, like form_for); it's best used for non-model forms (I actually only use it for simple search forms or the like).
form_tag只需创建一个表单标签(当然还默默地准备一个防伪隐藏字段,例如form_for);它最适合用于非模型表单(我实际上只将它用于简单的搜索表单等)。
Similarly, form_remote_forand form_remote_tagare suited for model related forms and not model related forms respectively but, instead of ending in a standard http method (GET, POST...), they call an ajax method.
同样,form_remote_for和form_remote_tag适合于模型有关的各种形式,而不是相关的形式分别进行建模,但是,而不是在一个标准的HTTP方法结束(GET,POST ...),他们称为AJAX方法。
All this and far more are available for you to enjoy in the FormHelperand PrototypeHelperreference pages.
您可以在FormHelper 中享受所有这些以及更多内容和PrototypeHelper参考页面。
EDIT2012-07-13
编辑2012-07-13
Prototypehas been removed from railslong ago, and remote forms have completely changed. Please refer to the first link, with reguard to the :remoteoption of both form_forand form_tag.
Prototyperails早就被移除了,远程表单已经完全改变了。请参阅第一个链接,与reguard的:remote两个选项form_for和form_tag。
回答by Matthias
These should be similar:
这些应该是相似的:
<% form_for @person do |f| %>
<%= f.text_field :name %>
<% end %>
and:
和:
<%= form_tag '/person' do %>
<%= text_field_tag "person[name]" %>
<% end %>
If you want to submit the same params to the controller, you would have to define this explicitly.
如果您想向控制器提交相同的参数,则必须明确定义它。

