Determine if path exists as route in Rails controller

孤者浪人 提交于 2019-12-02 00:32:30

问题


I want to know if an arbitrary path can be mapped to a route

recognized_request_for accomplishes what I want, but I can't get it to work in my controller.

Specifically, how can I execute recognized_request_for or something that accomplishes the same task from my controller?


回答1:


For Rails 3 the call is

Rails.application.routes.recognize_path

Instead of

ActionController::Routing::Routes.recognize_path

Example:

def path_exists?(path)
  begin
    Rails.application.routes.recognize_path(path)
  rescue
    return false
  end

  true
end



回答2:


SOLUTION:

@related_page_path = '/' + @page.path
begin
  ActionController::Routing::Routes.recognize_path(@related_page_path, :method => :get)
rescue
  @related_page_path = nil
end



回答3:


You could possibly dynamically generate the route helper method and see if it exists (using respond_to? or even just catching any thrown exception).




回答4:


If you want to connect an arbitrary path the a controller and and action, you can use map.connect

map.connect '/any/random/string/of/stuff', :controller => 'items', :action => 'new'

You can even call out embedded param designations in the path:

map.connect '/seeking/room/for/[:number_of_nights]/nights', :controller => 'rooms', :action => 'index'

with the above you will receive the value represented in the url as part of the params hash in the controller.




回答5:


I recently came across an issue where I had to check if a path existed given an array of possible paths. I had tried the above suggestion Rails.application.routes.recognize_path, but it's depericated as of rails 4.2.1. I used the following instead:

Rails.application.routes.named_routes.routes.any?{ |key, value| key.to_s === "new_article" }


来源:https://stackoverflow.com/questions/3273715/determine-if-path-exists-as-route-in-rails-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!