Rails是否使用方法:: patch与_form.html.erb进行编辑? [英] Does rails use method: :patch for editing with _form.html.erb?

查看:83
本文介绍了Rails是否使用方法:: patch与_form.html.erb进行编辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将遵循获取的Ruby on Rails教程指南开始,并且位于 5.12使用局部变量清除视图中的重复项。据D.R.Y,我了解为什么要使用分词。约定,但是,我对new.html.erb和edit.html.erb的区别感到好奇。具体来说,在使用部分_form.html.erb文件之前,edit.html.erb文件显式调用方法::patch

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">
...

...现在_form.html.erb文件涵盖了新的无需显式调用 PATCH

... 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">
...

是否仍在在幕后调用PATCH进行编辑? / p>

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

推荐答案

正如您在本教程中提到的:

As mentioned in the tutorial you shared:


我们可以使用这种较短,更简单的form_for声明来代表其他任何形式的原因是@article是与全套RESTful路由相对应的资源,并且Rails能够推断出哪个URI和方法

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.

另外,来自参考给出:

对于现有的资源记录 @post ,它是等效于:

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 %>

其中,对于资源的新记录,即 Post.new ,它等效于

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. 您为模型定义的路线,资源:商品

  2. 资源对象的类型(现有记录或新记录)传递给 form_for

  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.

这篇关于Rails是否使用方法:: patch与_form.html.erb进行编辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆