简体   繁体   中英

Does rails use method: :patch for editing with _form.html.erb?

I am following along with the Ruby on Rails tutorial guide for getting started and am in section 5.12 Using partials to clean up duplication in views . I understand why partials are used per the DRY convention, however, I am curious about a difference in the new.html.erb and edit.html.erb. Specifically, prior to using the partial _form.html.erb file, the edit.html.erb file explicitly called method: :patch

<%= form_for :article, url: article_path(@article), method: :patch do |f| %>
  <% if @article.errors.any? %>
    <div id="error_explanation">
...

... and now the _form.html.erb file covers both new & edit without explicitly calling PATCH :

<%= form_for @article do |f| %>

  <% if @article.errors.any? %>
    <div id="error_explanation">
...

Is PATCH still being invoked "behind the scenes" for editing?

Yes. form_for checks whether the model is persisted to know whether it needs to perform a POST (create) or PATCH (update).

As mentioned in the tutorial you shared:

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.

Also, from the reference given there:

For an existing resource or record for @post , it is equivalent to:

<%= form_for @post, as: :post, url: post_path(@post), method: :patch, html: { class: "edit_post", id: "edit_post_45" } do |f| %>
  ...
<% end %>

Whereas, for a new record of the resource, ie Post.new , it is equivalent to

<%= form_for @post, as: :post, url: posts_path, html: { class: "new_post", id: "new_post" } do |f| %>
  ...
<% end %>

Thus, in this case, magic lies in the rails with 2 things, helping rails understand what to do with this form:

  1. Your defined routes for your model, resources :article
  2. The type(Existing record or a new record) of resource object passed to form_for .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM