Ruby on Rails:根据路径获取控制器和操作名称
我正在尝试根据路径获取控制器和操作名称。我有一条路线:
map.resources :permissions
我想我可以使用:
ActionController::Routing::Routes.recognize_path "/permissions/1"
获得像这样的散列:
{ :controller => "permissions", :action => "show" }
返回的实际散列是:
{ :controller => "permissions", :action => "1" }
如何获得正确的操作名称,而不仅仅是我传入的 ID?调度程序必须能够以某种方式获取它,否则 Rails 将无法工作,但我无法找到它是如何完成的。
I am trying to get the controller and action name based on a path. I have a route:
map.resources :permissions
I thought that I could use:
ActionController::Routing::Routes.recognize_path "/permissions/1"
To get a hash like:
{ :controller => "permissions", :action => "show" }
The actual hash that comes back is:
{ :controller => "permissions", :action => "1" }
How do I get the correct action name instead of just my passed in ID? The dispatcher must be able to get at it somehow or Rails wouldn't work, but I am having trouble locating how it is accomplished.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 Rails 4 开始,识别路径的方法现在是
Rails.application.routes.recognize_path
,而不是ActionController::Routing::Routes.recognize_path
并且它返回一个哈希值控制器、操作和 id 如下所示:As of Rails 4 the method to recognize the path is now
Rails.application.routes.recognize_path
as opposed toActionController::Routing::Routes.recognize_path
and it returns a hash of controller, action, and id like so:你真正追求的是什么?如果您真的想要操作名称和控制器名称...您可以只询问
和
这有帮助吗,或者您真的需要解析字符串才能做到这一点吗?
What are you really after? If you're really after the action name and controller name... you can just ask for
and
Does that help, or do you really need to parse a string to do it?
这就是我最终所做的。这很丑陋,必须有更好的方法,但目前有效。它发生在 before_filter 中,以便我可以查看用户是否有权访问他们尝试访问的控制器/操作。
我选择使用基于路由的授权而不是基于模型的授权。
然后,您可以使用 request.params[:controller] 和 request.params[:action] 访问控制器和操作。
如果 ActionController::Routing::Routes.recognize_path("/permissions/1") 返回正确的操作,则所有这些都不是必需的。
This is what I ended up doing. It is ugly and there must be a better way, but it works for now. It happens in a before_filter so that I can see if the user has access to the controller / action they are attempting to access.
I chose to use route-based authorization as opposed to model-based authorization.
Then you access the controller and action with request.params[:controller] and request.params[:action].
All of this would not be necessary if ActionController::Routing::Routes.recognize_path("/permissions/1") returned the correct action.