Rails如何决定使用PUT或POST方法呈现表单? [英] How does rails decide to render a form with a method of PUT or POST?

查看:139
本文介绍了Rails如何决定使用PUT或POST方法呈现表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails生成一个表单部分,可以在get操作呈现的页面和新动作呈现的页面上使用。如果是前者,则表单的方法设置为PUT,如果后者将表单的操作设置为POST。



如何使用rails决定使用哪种方法?

解决方案

if传递给表单的对象是 持久? ,表单构建器知道您正在更新对象,并因此呈现 PUT 操作。如果它没有被持久化,那么它知道你正在创建一个新对象,它将使用 POST

 <%= form_for @user do | f | %GT; 
<%= f.button%>
<%end%>

如果 @user 是新记录,使用 POST ,按钮标签变为创建用户,否则 PUT 被使用并且标签变成更新用户。没有什么更多。


Rails generates a form partial that can be used on both the page rendered by a get action and a page rendered by a new action. If it is the former the form's method is set to PUT, if the latter the form's action is set to POST.

How does rails decide which method to use?

解决方案

if the object passed to the form is persisted?, the form builder knows that you are updating an object and will therefore render a PUT action. If it is not persisted, then it knows you are creating a new object and it will use POST.

<%= form_for @user do |f| %>
  <%= f.button %>
<% end %>

If @user is a new record, POST is used and the button label becomes Create User, otherwise PUT is used and the label becomes Update User. There's not much more to it.

这篇关于Rails如何决定使用PUT或POST方法呈现表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆