根据 RoR 约定从类名中检索控制器名称
我正在使用 Ruby on Rails 3.0.9,我想从类名构建控制器名称,并尽可能遵循 RoR 命名约定。例如,如果我有 Articles::Comment
类,我想检索 articles/comments
字符串。
也许开发人员创建了一个 RoR 方法来在内部处理这些约定,但我不知道。
如何检索上例中的控制器名称?
I am using Ruby on Rails 3.0.9 and I would like to build a controller name from a class name as well as possible following RoR naming conventions. For example, if I have the Articles::Comment
class I would like to retrieve the articles/comments
string.
Maybe it exists a RoR method created by developers to handle internally these conventions, but I don't know that.
How can I retrieve the controller name as in the example above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在寻找下划线方法。 更多信息。
或者,如果您已经有了控制器类本身,它会像这样:
编辑
至于路由,它们一次构建一个片段,即使您为它们命名空间也是如此。当你做这样的事情时:
Rails 要做的是,首先:
然后它将获得“评论”并执行相同的操作,但这个将被路由到“/articles”下。 Rails 没有命名空间内部资源,因此控制器必须是 CommentsController,而不是 Articles::CommentsController。
只有这样你才能清楚地命名某些东西,Rails 将为你的类命名空间:
我希望现在更清楚了。
You're looking for the underscore method. More info here.
Or, if you've got the controller class itself, it would be like this:
EDIT
As of routes, they are built one piece at a time, even when you namespace them. When you do something like this:
What rails is going to do is, first:
Then it's going to get "comments" and do the same, but this one is going to be routed under "/articles". Rails does not namespace internal resources, so, the controller has to be CommentsController, not Articles::CommentsController.
Only then you clearly namespace something, Rails is going to namespace your classes:
I hope it's clearer now.