我想知道api请求的路由是什么.
让我们说例如api_v1_user_session_path是/ api / v1 / users / sign_in url的路由
如果请求来自/ api / v1 / users / sign_in我如何找出路由是什么.在这种情况下,它应该是api_v1_user_session_path
我尝试了下面的声明,但它给出了控制器和动作但不是路线.
Rails.application.routes.recognize_path('/api/v1/users/sign_in') => {:controller=>"api/v1/sessions",:action=>"new"}
有这样的方法吗?
Rails.application.routes.get_route('/api/v1/users/sign_in') => api_v1_user_session
如何从url或request对象获取此路由.
解决方法
通过更多搜索,我能够自己解决这个问题.
class StringToRoute attr_reader :request,:url,:verb def initialize(request) @request = request @url = request.original_fullpath @verb = request.request_method.downcase end def routes Rails.application.routes.routes.to_a end def recognize_path Rails.application.routes.recognize_path(url,method: get_verb) end def process _recognize_path = recognize_path routes.select do |hash| if hash.defaults == _recognize_path hash end end end def get_verb verb.to_sym end def path "#{verb}_#{process.name}" end end
结果:
StringToRoute.new(请求).路径