简体   繁体   中英

Rails link_to sends POST and GET requests when you use method: :post

I trying to send a POST request via link_to in the following way:

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

My DiagnosisController has the action transition , but when I click on the link this sends two requests, a POST and a GET. The first request executes successfully, but the last one sends an unknown parameter to the show action and therefore returns an error.

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)

Does anyone know what I should do? Thanks in advance.


UPDATE:

When I try to do this it works normally

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

In your transition method in the diagnosis controller, after the action, there is a redirect that is redirecting you - that is what the second get request is.

You could just get rid of the redirect. Delete the part of your transition method that looks like this:

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

Also, just make sure your routes are declared

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

就我而言,我忘记在Application.js加载jquery_ujs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM