我正在使用 Ruby on Rails 3.0.9,我想根据类名构建 Controller 名称,并尽可能遵循 RoR 命名约定。例如,如果我有 Articles::Comment
类,我想检索 articles/comments
字符串。
也许它存在一个由开发人员创建的 RoR 方法来在内部处理这些约定,但我不知道。
如何像上面的示例一样检索 Controller 名称?
最佳答案
您正在寻找下划线方法。 More info here .
"Articles::Comment".underscore
或者,如果你有 Controller 类本身,它会是这样的:
Articles::Comment.name.underscore
编辑
就路由而言,它们是一次构建一个片段,即使您为它们命名空间也是如此。当你做这样的事情时:
map.resources :articles do |articles|
articles.resources :comments
end
rails 要做的是,首先:
"articles". classify # which yields "Article" then rails is going to append "Controller" to it
然后它将获得“评论”并做同样的事情,但是这个将被路由到“/articles”下。 Rails 没有命名空间内部资源,因此, Controller 必须是 CommentsController,而不是 Articles::CommentsController。
只有这样你才能清楚地为某些东西命名,Rails 才会为你的类命名:
map.namespace :admin do |admin|
admin.resources :articles # will require controller "Admin::ArticlesController"
end
我希望现在更清楚了。
关于ruby-on-rails - 按照 RoR 约定从类名中检索 Controller 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6824561/