Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 792
Fred Willmore Avatar asked Apr 25 '16 23:04

Fred Willmore


2 Answers

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"
like image 71
RalphShnelvar Avatar answered Nov 15 '22 06:11

RalphShnelvar


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"}
like image 29
Fred Willmore Avatar answered Nov 15 '22 07:11

Fred Willmore