【发布时间】:2019-06-04 15:47:28
【问题描述】:
我有一个带有remote: true 的表格,如下所示:
<%= form_with model: @transfer, scope: :transfer, url: transfers_path, method: 'post', remote: true do |f| %>
而我的控制器create 操作如下所示:
def create
@transfer = @account.transfers.build(transfer_params)
respond_to do |format|
if @transfer.save
format.html { redirect_to transfers_path }
else
format.js
end
end
end
如果我提交的表单没有错误,则页面会按预期重定向。但是,我注意到服务器响应的状态码是 200,而不是 302。我的服务器日志如下所示:
Started POST "/transfers" for ::1 at 2019-06-04 08:32:22 -0700
Processing by TransfersController#create as JS
...
Redirected to http://localhost:3000/transfers
Completed 200 OK in 1476ms (ActiveRecord: 81.2ms)
Started GET "/transfers" for ::1 at 2019-06-04 08:32:23 -0700
Processing by TransfersController#index as HTML
只是想知道为什么它是 200 而不是 302?我还意识到这永远不会起作用,因为我不应该能够使用 AJAX 请求进行重定向(如果我理解正确,remote: true 会发送 AJAX 请求)。
关于 SO 的其他问题的答案似乎表明 redirect_to 不起作用,我必须使用 JS 来设置重定向的窗口位置。一些示例答案:
- https://stackoverflow.com/a/23433009/3504731
- https://stackoverflow.com/a/37601358/3504731
- https://stackoverflow.com/a/16098942/3504731
我对我的代码为何能正常工作感到困惑。任何人都可以对此有所了解吗?我怀疑rails-ujs 在幕后做了一些魔术,但我不确定。具体来说,我怀疑 these lines 但我不太擅长 JS,我无法解析其中的大部分内容。我也在运行 Rails 5.2.1。
【问题讨论】: