articles_path 是如何工作的?(RubyOnRails 教程)

Fla*_*nix 4 ruby ruby-on-rails view

我正在关注官方的 Ruby on Rails 教程,并且刚刚完成第 5.9 章。

添加链接应该很简单,但我很困惑。

当我输入 时bin/rake routes,我得到以下输出:

fl4m3ph03n1x: ~/blog $ bin/rake routes
      Prefix Verb   URI Pattern                  Controller#Action
    articles GET    /articles(.:format)          articles#index
             POST   /articles(.:format)          articles#create
 new_article GET    /articles/new(.:format)      articles#new
edit_article GET    /articles/:id/edit(.:format) articles#edit
     article GET    /articles/:id(.:format)      articles#show
             PATCH  /articles/:id(.:format)      articles#update
             PUT    /articles/:id(.:format)      articles#update
             DELETE /articles/:id(.:format)      articles#destroy
        root GET    /                            welcome#index
fl4m3ph03n1x: ~/blog $  
Run Code Online (Sandbox Code Playgroud)

根据教程,这是有道理的。

为了利用这一点,我有一个观点:

<h1>New Article</h1>

<%= form_for :article, url: articles_path do |f| %>
  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

<%= link_to 'Back', articles_path %>
Run Code Online (Sandbox Code Playgroud)

该视图最后有一个提交表单和一个链接。根据 ruby​​,我通过使用articles_pathin指定表单中的提交按钮链接<%= form_for :article, url: articles_path do |f| %>

我真的不知道这个变量是如何设置的,但我会上钩并接受它。根据教程,点击提交按钮时articles_path默认会显示“POST /articles(.:format)articles#create”。

但是,在链接中<%= link_to 'Back', articles_path %>articles_path应该将我们重定向到索引页面......

有人可以解释一下同一个变量如何在同一个视图中有两种截然不同的行为吗?

Ahm*_*uty 5

动作视图方法如何工作:

link_to默认请求类型是“GET”。

button_to默认请求类型是“POST”。

每个生成的路由都有一个特定的类型,这就是 Rails 如何将不同的请求映射到正确的请求的方式。

对于form_for操作视图帮助器方法,它会根据您是否将实例传递给表单来自动区分“POST”和“PUT”。

您还可以通过添加显式提供表单的方法类型

method: 'GET' OR :html => { :method => 'GET' }
Run Code Online (Sandbox Code Playgroud)

** 根据 Rails 版本检查不同的语法功能。

其他方法也是如此,所以如果你想link_to发送 post 请求,你必须传递method="POST"给它。


** Rails 如何区分索引和显示操作 **

在生成的路由表中,您可能已经注意到索引操作不需要实例 ID,因为它应该列出所有文章。但是,对于显示,您需要向其传递一个实例,因为它应该仅显示特定的实例。

= link_to "index", articles_path
= link_to "show", article_path(article)
Run Code Online (Sandbox Code Playgroud)

注意 ::

两种方法不一样,“冠词”和“冠词”,复数 vs 单数。即使它们的名称相同,其中一个也会出现实例,而另一个则不会。