当你使用method :: post时,Rails link_to发送POST和GET请求

时间:2017-02-08 20:42:51

标签: ruby-on-rails link-to

我尝试通过link_to以下列方式发送POST请求:

link_to 'go to transition', transition_diagnosis_path, method: :post

我的DiagnosisController有动作transition,但当我点击链接时,会发送两个请求,一个POST和一个GET。第一个请求成功执行,但最后一个请求向show操作发送一个未知参数,因此返回错误。

Started POST "/diagnosis/transition" for 127.0.0.1 at 2017-02-08 17:45:32 -0200
Processing by DiagnosisController#transition as HTML
  Parameters: {"authenticity_token"=>"XXXXXXXXXXXXX"}
Redirected to http://localhost:3000/analysis
Completed 302 Found in 1126ms (ActiveRecord: 128.0ms)

Started GET "/diagnosis/transition" for 127.0.0.1 at 2017-02-08 17:45:33 -0200
Processing by DiagnosisController#show as HTML
  Parameters: {"id"=>"transition"}
Completed 500 Internal Server Error in 975ms (ActiveRecord: 24.8ms)

有谁知道我应该怎么做?提前谢谢。

更新:

当我尝试这样做时,它可以正常工作

link_to transition_diagnosis_path, method: :post do
  button_tag 'go to transition'
end

1 个答案:

答案 0 :(得分:0)

在诊断控制器的转换方法中,在操作之后,有一个重定向正在重定向您 - 这就是第二个获取请求。

你可以摆脱重定向。删除过渡方法中看起来像这样的部分:

respond_to do |format|
    format.js { render :nothing => true }
    format.html { redirect_to home_url }
end

此外,只需确保您的路线已宣布

post 'diagnosis/transition', to: 'diagnosis#transition'