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

北城余情 提交于 2019-12-25 08:59:14

问题


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?


回答1:


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.



回答2:


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



来源:https://stackoverflow.com/questions/43795769/does-rails-use-method-patch-for-editing-with-form-html-erb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!