Ruby-on-rails 获取完整的 rails 控制器名称,包括命名空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5273503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:39:20  来源:igfitidea点击:

Get full rails controller name, including the namespace

ruby-on-railsruby-on-rails-3

提问by cytrinox

I've many controllers in different namespaces. The controller_name method only returns the name of the controller, e.g. 'articles'. Is there any chance to get the full name like 'service/articles' (the articles controller is in the service namespace)?

我在不同的命名空间中有很多控制器。controller_name 方法只返回控制器的名称,例如'articles'。有没有机会获得像“服务/文章”这样的全名(文章控制器在服务命名空间中)?

I want do create a link to the index action of each controller via a globally used partial:

我想通过全局使用的部分创建指向每个控制器的索引操作的链接:

<%= link_to controller.display_name, { :controller => controller.controller_name, :action => "index"} %>

If this partial is rendered in a view in the 'users' namespace, I get an error: users/articles has no route (it should be service/articles).

如果此部分呈现在“用户”命名空间的视图中,我会收到一个错误:用户/文章没有路由(它应该是服务/文章)。

回答by Jesse Wolgamott

Instead of linking to the :controller, :action syntax, can you use nested resources

您可以使用嵌套资源,而不是链接到 :controller, :action 语法

routes.rb

路由文件

resources :users do
  resources: articles
end

in your view

在你看来

= link_to 'Articles', user_article_path(current_user)

The user_article will take care of your namespaces for you.

user_article 将为您处理您的命名空间。