根据 RoR 约定从类名中检索控制器名称

发布于 2024-11-26 03:38:19 字数 228 浏览 1 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠北森屋 2024-12-03 03:38:19

您正在寻找下划线方法。 更多信息

"Articles::Comment".underscore

或者,如果您已经有了控制器类本身,它会像这样:

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 没有命名空间内部资源,因此控制器必须是 CommentsController,而不是 Articles::CommentsController。

只有这样你才能清楚地命名某些东西,Rails 将为你的类命名空间:

map.namespace :admin do |admin|
  admin.resources :articles # will require controller "Admin::ArticlesController"
end

我希望现在更清楚了。

You're looking for the underscore method. More info here.

"Articles::Comment".underscore

Or, if you've got the controller class itself, it would be like this:

Articles::Comment.name.underscore

EDIT

As of routes, they are built one piece at a time, even when you namespace them. When you do something like this:

map.resources :articles do |articles|
  articles.resources :comments
end

What rails is going to do is, first:

"articles". classify # which yields "Article" then rails is going to append "Controller" to it

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:

map.namespace :admin do |admin|
  admin.resources :articles # will require controller "Admin::ArticlesController"
end

I hope it's clearer now.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文