简体   繁体   English

如何从Rails的控制器中访问路由信息(HTTP动词,动作名称等)?

[英]How do I access the route information (HTTP verb, action name, etc . . .) from within a controller in Rails?

Say I'm within a controller and I want to get a list of the actions and HTTP verbs that it supports, how would I do that?. 假设我在控制器内,并且想要获得其支持的动作和HTTP动词的列表,我该怎么做? Eg 例如

controller.actions # { [ :show, :get ], [ :update, :put ], . . .  }

Or something equivalent. 或等效的东西。

Something like this: 像这样:

controller = "users"
controller_routes = []
Rails.application.routes.routes.each do |route|
  if route.to_s.include?(":controller=>\"#{controller}\"")  
    controller_routes << route
  end  
end
puts controller_routes

You get the idea. 你明白了。

To list the http methods (GET, POST, PUT, DELETE) that are valid for each controller's actions run: 要列出对每个控制器的操作有效的http方法 (GET,POST,PUT,DELETE),请运行:

rake routes

It will list which http methods are configured for all controllers. 它将列出为所有控制器配置的http方法。

You change which http methods are used by editing /config/routes.rb 您可以通过编辑/config/routes.rb来更改使用哪些http方法

The RailsGuide includes a great explanation here . RailsGuide 在此提供了很好的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM