Rails.application.routes.recognize_path无法识别POST路由

Fre*_*ore 5 ruby-on-rails

我正在使用Rails.application.routes.recognize_path将路径分解为其组件--:controller,:action,:id等.它似乎与GET路由一起正常工作,但是对于POST路由,它会变空.这是我的路线文件的相关部分:

resources :units do
  member do
    get :test_get
    post :test_post
  end
end
Run Code Online (Sandbox Code Playgroud)

以下是GET的recogn_path的输出:

Rails.application.routes.recognize_path '/units/1/test_get'
=> {:controller=>"units", :action=>"test_get", :id=>"1"}  
Run Code Online (Sandbox Code Playgroud)

这是POST的输出:

Rails.application.routes.recognize_path '/units/1/test_post'
ActionController::RoutingError: No route matches "/units/1/test_post"
Run Code Online (Sandbox Code Playgroud)

路线已定义 - 这是输出 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
Run Code Online (Sandbox Code Playgroud)

我的道路上缺少什么?我应该使用另一种方法吗?

Ral*_*var 12

让我来扩大这个答案.

我遇到了完全相同的问题.我有

@controller_action_hash = Rails.application.routes.recognize_path(request.url)
Run Code Online (Sandbox Code Playgroud)

在application_controller.rb中.这导致Rails 4做了

ActionController::RoutingError (No route matches "http://localhost:3000/internal_users/sign_out"):
Run Code Online (Sandbox Code Playgroud)

(我正在使用Devise).

这导致我走下兔子洞检查routes.rb,运行rake路线,并在Devise中跟踪代码.

解决问题

在我的情况下,以下工作

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

就我而言

request.env["REQUEST_METHOD"]   # => "DELETE"
Run Code Online (Sandbox Code Playgroud)


Fre*_*ore 8

找到了!识别路径接受第二个参数,选项的散列,其中之一是:方法。所以这有效:

Rails.application.routes.recognize_path '/units/1/test_post', method: :post
 => {:controller=>"units", :action=>"test_post", :id=>"1"}
Run Code Online (Sandbox Code Playgroud)