Ruby-on-rails Rails - 控制器动作名称到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1244921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:36:59  来源:igfitidea点击:

Rails - controller action name to string

ruby-on-railsfunction

提问by Pavel K.

I have a Rails question.

我有一个 Rails 问题。

How do I get a controller action's name inside the controller action?

如何在控制器操作中获取控制器操作的名称?

For example, instead of

例如,代替

def create
  logger.info("create")
end

I want to write something like

我想写一些类似的东西

def create
  logger.info(this_def_name)
end

What is a way to get this_def_name?

有什么办法获得this_def_name

回答by JellicleCat

Rails 2.X: @controller.action_name

轨道 2.X@controller.action_name

Rails 3.1.X: controller.action_name, action_name

Rails 3.1.X: controller.action_name,action_name

Rails 4.X: action_name

导轨 4.Xaction_name

回答by mikej

In the specific case of a Rails action (as opposed to the general case of getting the current method name) you can use params[:action]

在 Rails 操作的特定情况下(与获取当前方法名称的一般情况相反),您可以使用 params[:action]

Alternatively you might want to look into customising the Rails log format so that the action/method name is included by the format rather than it being in your log message.

或者,您可能希望研究自定义 Rails 日志格​​式,以便操作/方法名称包含在格式中,而不是包含在日志消息中。

回答by dumP

controller name:

控制器名称:

<%= controller.controller_name %>

return => 'users'

返回 => '用户'

action name:

动作名称:

<%= controller.action_name %>

return => 'show'

返回 => '显示'

id:

ID:

<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>

return => '23'

返回 => '23'

回答by Vladimir Kroz

This snippet works for Rails 3

此代码段适用于 Rails 3

class ReportsController < ApplicationController

  def summary
    logger.debug self.class.to_s + "." + self.action_name
  end

end

will print

将打印

. . .
ReportsController.summary
. . .

. . .
ReportsController.summary
。. .

回答by Pavel K.

mikej's answer was very precise and helpful, but the the thing i also wanted to know was how to get current method name in rails.

mikej 的回答非常准确和有帮助,但我还想知道的是如何在 rails 中获取当前方法名称。

found out it's possible with self.current_method

发现 self.current_method 是可能的

easily found at http://www.ruby-forum.com/topic/75258

http://www.ruby-forum.com/topic/75258很容易找到

回答by Rushabh Ajay Hathi

I just did the same. I did it in helper controller, my code is:

我只是做了同样的事情。我是在辅助控制器中完成的,我的代码是:

def get_controller_name
  controller_name    
end


def get_action_name
  action_name   
end

These methods will return current contoller and action name. Hope it helps

这些方法将返回当前控制器和操作名称。希望能帮助到你