从类名中检索控制器名称
我正在使用 Ruby on Rails 3.0.7,我想检索给定类名的控制器名称。也就是说,我已经
Articles::Category
并且想要检索
articles/categories
我想要检索与 Articles::Categories
控制器无关的视图文件内的控制器名称。
我该如何做到这一点(可能使用一些 Ruby on Rails 核心方法)?
I am using Ruby on Rails 3.0.7 and I would like to retrieve a controller name given a class name. That is, I have
Articles::Category
and I would like to retrieve
articles/categories
I would like to retrieve the controller name inside a view file not related to the Articles::Categories
controller.
How can I do that (possibly using some Ruby on Rails core method)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如许多其他人提到的,没有特殊的方法。但只要您遵循 Rails 约定,这种方法就会带您走得更远。
As mentioned by many others, there is no special method for that. But as long as you followed Rails conventions, this approach will take you far.
要获取控制器名称,例如在视图内,您可以执行以下操作:
要获取类的名称,例如 User,如果您有一个名为 user 的用户对象:
除此之外,我认为控制器之间没有相关性和一个模型,它可以从类名中为您提供控制器名称,因为它们是不同的东西。您也许可以创建一个像 {:controller =>; 一样的哈希值。 'class_name'} 并自己映射它们。
To get the controller name, say inside your view, you can do :
To get the name of a class, say User, if you have a user object named user :
Other than that, i don't think there's a correlation between a controller and a model, that can give you the controller name from a class name, because they are different things. You can maybe create a hash like {:controller => 'class_name'} and map those yourself.
它强调驼峰式单词,以便:
And it underscores camelcased words to so that:
假设您真正的意思是
Articles::CategoriesController
那么Articles::CategoriesController.controller_path
将为您提供您想要的内容。更新 问题是,给定 Rails 模型的名称,如何获取关联控制器的名称?
这个问题的答案是,你不能。模型名称到控制器名称不存在一对一的映射。
User
模型可以由users_controller.rb
和/或admin/users_controller.rb
控制,或者根本没有关联的控制器。您当然可以根据 Rails 约定猜测一些可能的可能性,但您无法知道。Assuming that you really meant
Articles::CategoriesController
thenArticles::CategoriesController.controller_path
will give you what you want.Update The question is, given the name of a Rails Model, how do you get the name of the associated controller?
The answer to that question is, you can't. There is not a one-to-one mapping from the model name to the controller name. The
User
model could be controlled by theusers_controller.rb
and/oradmin/users_controller.rb
or not have an associated controller at all. You can certainly guess at some likely possibilities based on Rails conventions but you can't know.而不是
underscore.pluralize
只需使用表化
:Instead of
underscore.pluralize
just usetableize
: