Wednesday, May 4, 2016

Application wide partials



Just a short tip for my readers about application wide partials, those partial like headers or footers appearing in all your pages.

Sometimes our first idea is to place these partials under a certain controller's views. For instance, I have a Site controller

class SiteController < ApplicationController

  def homepage
  end

end

such that in config/routes.rb we have

root 'site#homepage'

and in app/views/site/homepage.html.erb we render a partial named footer with

render 'footer'

Our first idea may be storing footer's contents inside app/views/site/_footer.html.erb, but this is not a good idea. If we do so, trying to render this footer from other controller's view, say Admin controller, would result in an error. To avoid this error we would have to do it like

render 'site/footer'

Nothing so difficult in this, of course. But there is a less known way to do the same without this.

You may create a directory named app/views/application and all partials under this directory will be within the scope of ApplicationController, Thus, they may be rendered wherever you want, disregarding the controller whose method is being executed.

In fact, in my opinion this folder app/views/application should be created by default when the application was created with rails new [application_name].