[Rails]表单提交时,post与patch的内部转化

3 篇文章 0 订阅

在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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值