[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/

0 0
原创粉丝点击