Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get full rails controller name, including the namespace

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)?

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).

like image 691
cytrinox Avatar asked Mar 11 '11 13:03

cytrinox


People also ask

What is namespace controller?

The namespace property is optional and defines a namespace for a controller. Multiple controllers may be defined in the same namespace. Multiple controllers may be defined with the same name as long as they are defined in separate packages and are not defined in the same namespace.

What is namespacing Rails?

Namespacing is a way of bundling logically related objects together. Modules serve as a convenient tool for this. This allows classes or modules with conflicting names to co-exist while avoiding collisions. Think of this as storing different files with the same names under separate directories in your filesystem.


2 Answers

Have you tried:

controller_path

http://api.rubyonrails.org/classes/AbstractController/Base.html#method-i-controller_path

like image 91
johnmcaliley Avatar answered Oct 19 '22 09:10

johnmcaliley


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

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.

like image 25
Jesse Wolgamott Avatar answered Oct 19 '22 10:10

Jesse Wolgamott