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.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With