Custom templates path for controller
railsSometimes you need to break rails’ conventions a little bit and set custom path for all templates per controller. Especially for the purpose of namespacing.
For example, you have a controller:
class UserGroupsController < ApplicationController
def index
end
def show
end
end
By default, rails will search for templates in app/views/user_groups
.
But what if you want to put those templates in app/views/users/groups
?
Instead of this:
class UserGroupsController < ApplicationController
def index
render 'users/groups/index'
end
def show
render 'users/groups/show'
end
end
You can do this:
class UserGroupsController < ApplicationController
def self.controller_path
'users/groups'
end
def index
end
def show
end
end
However, this will break controller’s spec.
There is another way to do this, however, with another limitation:
class UserGroupsController < ApplicationController
prepend_view_path 'app/views/users'
def index
end
def show
end
end
Now rails will search for templates in app/views/users/user_groups
. The limitation is that you must name a folder for your templates like a controller. For example, you cannot use app/views/users/groups
as a folder for templates for UserGroupsController
. You must name this folder app/views/users/user_groups
because of the controller’s name.
Conclusion
There are couple ways to set custom templates path per controller. Both have their downsides as a price for breaking conventions.