Does rails use method: :patch for editing with _fo

2019-08-17 11:10发布

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 D.R.Y. 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?

2条回答
Anthone
2楼-- · 2019-08-17 11:40

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, i.e. 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.
查看更多
叼着烟拽天下
3楼-- · 2019-08-17 11:53

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

查看更多
登录 后发表回答