如何从 Rails 3 中的视图/助手中检索控制器类?
我知道 controller_name
返回包含控制器名称的字符串,但如何从助手中检索控制器类(或对象)?
编辑:当控制器具有命名空间时,该解决方案也应该有效(例如Admin::PostsController
)
I know about controller_name
returning a string containing the controller's name but how can I retrieve the controller class (or object) from within a helper?
EDIT: The solution should also work when the controller is namespaced (eg. Admin::PostsController
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
constantize
方法,例如:虽然我不确定如果您有命名空间控制器,它会如何表现。
更新:
该方法不适用于所有控制器名称和/或命名空间。虽然可以将
#controller
方法与#class
结合使用:You can use the
constantize
method, like:Though I'm not sure how it will behave if you have a namespaced controller.
Update:
That one won't work for all controller names and/or namespaces. Though one can use the
#controller
method in combination with#class
:视图可能不需要这样做。理想情况下,无论您在视图中尝试执行什么操作,都应该在控制器中执行。
尝试思考为什么要这样做,我能想到的最好答案是您想调用在控制器中定义的辅助方法。已经存在一个构造可以执行此操作,请使用 helper_method。
对于几乎所有其他事情,控制器应该向视图提供该数据。不是将其从控制器中拉出的视图。 (例如,即使您不需要该类,控制器也可以为其提供
@controller_class = self.class
,然后视图即可使用该类)A view probably shouldn't need to do this. Ideally whatever you're trying to do in the view that expects this, you would instead do in the controller.
Trying to think about why you'd want to do this, the best answer I can think of is that you want to invoke a helper method you've defined in the controller. There already exists a construct to do this, use helper_method.
For pretty much anything else, the controller should provide that data to the view. Not the view pulling it out of the controller. (e.g. even though you shouldn't need the class, the controller could provide it with
@controller_class = self.class
, which would then be available to the view)在纯 Ruby 中,因为类名是常量,所以您可以这样做从字符串中获取类:
Rails 中有一个很好的快捷方式,
constantize
就是为了这样:如果类名是例如“editable_file” ,首先调用
camelize
方法:编辑:如果您确实想获得未解调的控制器名称,则此代码位于
config/initializers/controller_name.rb
应确保:In pure Ruby, because class names are constants, you can do this to get the class from a string:
There is a nice shortcut in Rails,
constantize
for just this:If the classname is eg 'editable_file', first call the
camelize
method:EDIT: If you really want to get the controller name un-demodulized, then this code in
config/initializers/controller_name.rb
should ensure it: