【问题标题】:Does rails use method: :patch for editing with _form.html.erb?Rails 是否使用 method::patch 来使用 _form.html.erb 进行编辑?
【发布时间】:2017-05-05 02:57:00
【问题描述】:

我正在关注getting started 的 Ruby on Rails 教程指南,并在 5.12 Using partials to clean up duplication in views 部分。我了解why partials are used 根据 D.R.Y.但是,我很好奇 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 进行编辑?

【问题讨论】:

    标签: ruby-on-rails rest erb


    【解决方案1】:

    是的。 form_for 检查模型是否被持久化以了解它是否需要执行POST(创建)或PATCH(更新)。

    【讨论】:

      【解决方案2】:

      正如您分享的教程中所述:

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

      另外,来自那里的reference

      对于现有的resourcerecord 对于@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 理解如何处理这个表单:

      1. 您为模型定义的路线,resources :article
      2. resource 对象的类型(现有记录或新记录)传递给form_for

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-21
        • 2013-07-23
        • 1970-01-01
        • 2023-03-25
        • 2014-05-01
        • 2017-12-17
        相关资源
        最近更新 更多