[Rails]表单提交时,post与patch的内部转化
来源:互联网 发布:通信网络设计师是什么 编辑:程序博客网 时间:2024/06/08 06:39
在route.rb中,写下resourses :adminuser
后,routes match产生了如下内容:
update和creat同样作为表单提交调用的action,却使用着不同的协议:post/patch(put)
。我们先来简单介绍一下patch和put协议:
patch:
当资源存在时,部分更新资源,例如更新某一个字段;
当资源不存在时,则创建一个新的资源,像SaveOrUpdate 操作。put:
当资源存在时,用于更新某个资源较完整的内容,比如说用户要重填完整表单更新所有信息,后台处理更新时可能只是保留内部记录 ID 不变;
当资源不存在时,PUT 只对已有资源进行更新操作,所以是 update 操作。
那么,我们再回过头来看在rails中,view是如何实现的:
<%= form_for(@user) do |f| %> <%= render 'shared/error_messages', object: @user %> <%= f.label :name %> <%= f.text_field :name, class: 'form-control' %> <%= f.label :email %> <%= f.email_field :email, class: 'form-control' %> <%= f.label :password %> <%= f.password_field :password, class: 'form-control' %> <%= f.label :password_confirmation %> <%= f.password_field :password_confirmation, class: 'form-control' %> <%= f.submit yield(:button_text), class: "btn btn-primary" %><% end %>
我们发现,在update和create两个表单中,ruby的描述完全相同。再看一下,在update页面中,转化成的html:
<form accept-charset="UTF-8" action="/users/1" class="edit_user" id="edit_user_1" method="post"> <input name="_method" type="hidden" value="patch" /> . . .</form>
rails已经自动判断出来是post还是patch。原因何在呢?
The answer is that it is possible to tell whether a user is new or already exists in the database via Active Record’s new_record? boolean method:
$ rails console> User.new.new_record?=> true> User.first.new_record?=> false
When constructing a form using form_for(@user), Rails uses POST if @user.new_record? is true and PATCH if it is false.
参考:
1. https://www.railstutorial.org/book/updating_and_deleting_users
2. http://unmi.cc/restful-http-patch-method/
- [Rails]表单提交时,post与patch的内部转化
- 关于表单提交时的get与post方法!
- POST与GET提交表单的区别
- POST与GET提交表单的区别
- 表单提交 get 与post的区别
- HTML中<form>表单利用 post 提交与利用 get 提交时的区别
- 表单提交方式get与post的区别
- CGI提交表单的两种方式POST与GET
- 表单的常用提交方式:get与post
- 表单中post与get进行提交的区别
- 表单中 get与post提交方法的区别
- form表单提交get与post的区别
- 表单提交post与get方法
- Form表单提交 get与post区别
- 提交表单--get与post方式
- 前台post提交表单时获取不到数据的原因
- php表单提交时获取不到post数据的解决方法
- 表单的提交方式POST和GET
- Springmvc+Spring+Hibernate中@Valid的使用
- 安卓学习笔记---实现下拉图片放大,松开又自动回去效果 (ListView与ScrollView)
- 获取文件类型、扩展名
- java学习之swing和JFC
- JS中this的作用
- [Rails]表单提交时,post与patch的内部转化
- 如何计算程序时间复杂度(实战篇)
- Tunnel:论如何在内网中自由渗透 20160721
- 界门纲目科属种
- SSH对于web.xml的配置
- 关于Android Launcher3相关优秀文章的记录
- 揭秘:攻击者如何在Kali Linux中搭建钓鱼热点 20160720
- js时间戳转成date
- Express框架学习