rails 是否使用 method::patch 与 _form.html.erb 一起编辑?
Does rails use method: :patch for editing with _form.html.erb?
我正在按照 D.R.Y Rails getting started and am in section 5.12 Using partials to clean up duplication in views. I understand why partials are used 教程指南中的 Ruby 进行操作。然而,我对 new.html.erb 和 edit.html.erb 的区别感到好奇。具体来说,在使用部分 _form.html.erb 文件之前,edit.html.erb 文件明确调用 method: :patch
<%= form_for :article, url: article_path(@article), method: :patch do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
...
...现在 _form.html.erb 文件涵盖了新建和编辑,而无需显式调用 PATCH:
<%= form_for @article do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
...
是否仍在调用 PATCH "behind the scenes" 进行编辑?
是的。 form_for
检查模型是否持久化以了解它是否需要执行 POST
(创建)或 PATCH
(更新)。
如您分享的教程中所述:
The reason we can use this shorter, simpler form_for declaration to stand in for either of the other forms is that @article is a resource corresponding to a full set of RESTful routes, and Rails is able to infer which URI and method to use.
此外,根据那里给出的 reference:
对于现有的 resource
或 record
对于 @post
,它等同于:
<%= form_for @post, as: :post, url: post_path(@post), method: :patch, html: { class: "edit_post", id: "edit_post_45" } do |f| %>
...
<% end %>
而对于资源的新记录,即Post.new
,相当于
<%= form_for @post, as: :post, url: posts_path, html: { class: "new_post", id: "new_post" } do |f| %>
...
<% end %>
因此,在这种情况下,魔术在于 rails 两件事,帮助 rails 了解如何处理此表单:
- 您为模型定义的路线,
resources :article
- 传递给
form_for
的 resource
对象的类型(现有记录或新记录)。
我正在按照 D.R.Y Rails getting started and am in section 5.12 Using partials to clean up duplication in views. I understand why partials are used 教程指南中的 Ruby 进行操作。然而,我对 new.html.erb 和 edit.html.erb 的区别感到好奇。具体来说,在使用部分 _form.html.erb 文件之前,edit.html.erb 文件明确调用 method: :patch
<%= form_for :article, url: article_path(@article), method: :patch do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
...
...现在 _form.html.erb 文件涵盖了新建和编辑,而无需显式调用 PATCH:
<%= form_for @article do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
...
是否仍在调用 PATCH "behind the scenes" 进行编辑?
是的。 form_for
检查模型是否持久化以了解它是否需要执行 POST
(创建)或 PATCH
(更新)。
如您分享的教程中所述:
The reason we can use this shorter, simpler form_for declaration to stand in for either of the other forms is that @article is a resource corresponding to a full set of RESTful routes, and Rails is able to infer which URI and method to use.
此外,根据那里给出的 reference:
对于现有的 resource
或 record
对于 @post
,它等同于:
<%= form_for @post, as: :post, url: post_path(@post), method: :patch, html: { class: "edit_post", id: "edit_post_45" } do |f| %>
...
<% end %>
而对于资源的新记录,即Post.new
,相当于
<%= form_for @post, as: :post, url: posts_path, html: { class: "new_post", id: "new_post" } do |f| %>
...
<% end %>
因此,在这种情况下,魔术在于 rails 两件事,帮助 rails 了解如何处理此表单:
- 您为模型定义的路线,
resources :article
- 传递给
form_for
的resource
对象的类型(现有记录或新记录)。