简体   繁体   中英

Rails.application.routes.recognize_path does not recognize POST route

I am using Rails.application.routes.recognize_path to decompose a path into its components - :controller, :action, :id, etc. It seems to work fine with GET routes, but with POST routes it comes up empty. Here is the relevant part of my routes file:

resources :units do
  member do
    get :test_get
    post :test_post
  end
end

Here is the output from recognize_path for GET:

Rails.application.routes.recognize_path '/units/1/test_get'
=> {:controller=>"units", :action=>"test_get", :id=>"1"}  

Here is the output for POST:

Rails.application.routes.recognize_path '/units/1/test_post'
ActionController::RoutingError: No route matches "/units/1/test_post"

The route is defined - here is the output from rake routes

test_get_unit GET     /units/:id/test_get(.:format)  units#test_get
test_post_unit POST   /units/:id/test_post(.:format) units#test_post

What's missing from my path? Is there another method I should be using?

Let me amplify this answer.

I ran into exactly the same problem. I had

@controller_action_hash = Rails.application.routes.recognize_path(request.url)

in application_controller.rb. This caused Rails 4 to do a

ActionController::RoutingError (No route matches "http://localhost:3000/internal_users/sign_out"):

(I'm using Devise).

This caused me to go down a rabbit hole checking routes.rb, running rake routes, and tracing through code in Devise.

Fixing the problem

In my case the following worked

@controller_action_hash = Rails.application.routes.recognize_path(request.url, method: request.env["REQUEST_METHOD"])

In my case

request.env["REQUEST_METHOD"]   # => "DELETE"

Found it! recognize_path takes a second parameter, a hash of options, one of which is :method. So this works:

Rails.application.routes.recognize_path '/units/1/test_post', method: :post
 => {:controller=>"units", :action=>"test_post", :id=>"1"}

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