为什么 Turbo 不支持 link_to 方法::post?

问题描述 投票:0回答:5

长期以来,Rails 在

method: :post
帮助器中提供了
link_to
选项:当给出该选项时,Rails 会拦截点击并发出 POST 请求,而不是默认的 GET 请求。

但是,由于某种未知的原因,这在 Rails 7 中不起作用:尽管将

method: :post
添加到我的
link_to
帮助器中,Rails 仍发送 GET 请求(而不是 POST 请求)。我以为 Turbo 应该解决这个问题,但似乎并没有发生。

这是您可以执行的重现操作,非常简单的步骤:

$ rails new example_app
$ bin/rails g scaffold Book title
$ bin/rails db:create && bin/rails db:migrate
$ echo "<%= link_to "New book", new_book_path, method: :post %>" >> app/views/books/index.html.erb
$ bin/rails s

现在从网络浏览器访问

localhost:3000/books
,然后单击第二个“新书”链接。我预计会收到错误(毕竟,我没有配置正确的 POST 路由),但不幸的是,Rails 发出 GET 请求 - 而不是 POST 请求,因为它应该有:

Started GET "/books/new" for ::1 at 2021-12-27 17:40:43 +0100
Processing by BooksController#new as HTML
  Rendering layout layouts/application.html.erb
  Rendering books/new.html.erb within layouts/application
  Rendered books/_form.html.erb (Duration: 9.1ms | Allocations: 5216)
  Rendered books/new.html.erb within layouts/application (Duration: 10.2ms | Allocations: 5594)
  Rendered layout layouts/application.html.erb (Duration: 12.9ms | Allocations: 7759)
Completed 200 OK in 25ms (Views: 13.6ms | ActiveRecord: 4.3ms | Allocations: 12404)

为什么会出现这种情况? Turbo 不应该拦截该链接,并且像 Rails UJS 过去那样发送 POST 请求吗?

turbo ruby-on-rails-7
5个回答
15
投票

在我看来,Rails 7 文档尚未针对 Turbo 和缺失的 UJS 库进行更新。尽管 link_to 文档 明确指出

link_to(..., ..., method: :post)
应该有效,但它显然不起作用。

深入研究 Turbo 的文档,有一个名为“使用不同方法执行访问”的部分,其中提到使用 link_to ..., ..., data: { 'turbo-method' => :post },这确实有效。

    


5
投票
不同:

固定@rails/ujs

$ bin/importmap pin @rails/ujs

然后在application.js中添加:
import Rails from "@rails/ujs"
Rails.start()

并且
link_to "...", "...", method: :delete
开始为我工作。

当您的遗留应用程序带有一堆 
method:

链接并且您不想将它们更改为

turbo-method:

 时,请考虑此解决方案
    

Rodrigo Serrano 的答案适用于 POST。但是,如果

0
投票
设置为

:delete

,并且在销毁操作中使用 
redirect_to
,则在 302 重定向后,将会对重定向到的资源触发 
destroy
 操作。
button_to

没有这个问题。

我使用的是 Rails 7.0.1。有一个未解决的问题 
https://github.com/hotwired/turbo-rails/issues/259

.

在 ruby 中遇到同样的问题

0
投票

rails 7

post
 方法未被执行,并作为 
get
 请求被拦截。现在使用快速修复方法,将 link_to 更改为按钮。
<%= button_to "Logout", :logout, method: :post %>

以防万一有人遇到这个问题..我自己也为此奋斗了一段时间,直到出现了一些问题。当在 Rails 上启用 Turbo 时,似乎有些东西是在 

0
投票
后面命名的。我还不完全理解,但我确实知道这一点,所以我想我会贡献我的发现。

以下 
link_to

发送

 POST 请求。
<%= link_to 'Click here', your_path(), data: { turbo_method: :post } %>

这行不通:
    <%= link_to 'Click here', your_path(), turbo_method: :post  %>


© www.soinside.com 2019 - 2024. All rights reserved.