Global rails partials

One of the most common practices I've seen in rails is to have an "app/views/shared" folder and render partial: “shared/my_partial”.

There is nothing wrong with this, but it is unnecessary. Ruby on Rails has a default convention to look for partials in app/views/application. If you rename your shared folder to the application, you can save yourself some characters and just type render partial: “my_partial”.

How did I end up here?

Well, I tried to render a partial that didn't exist and found myself with the following error:

<%= render partial: "missing_partial" %>

Missing partial pages/_missing_partial, 
                application/_missing_partial 
                with {
                  :locale=>[:en], :formats=>[:html], :variants=>[], 
                  :handlers=>[:raw, :erb, :html, :builder, :ruby]
                }. Searched in: * "/Users/mhenrixon/Code/mhenrixon/railsapp/app/views"

Aha! I requested the root page, which resides in the pages controller, so it checks the app/views/pages/ first for that partial, but what is the second one? app/views/application/ after a few minutes of research, it was clear from the rails documentation that:

The lookup order for an admin/products#index action will be:

  • app/views/admin/products/
  • app/views/admin/
  • app/views/application/

This makes app/views/application/ a great place for your shared partials, which can then be rendered in your ERB as such:

lang-erb
<%# app/views/admin/products/index.html.erb %>
<%= render @products || "empty_list" %>

<%# app/views/application/_empty_list.html.erb %>
There are no items in this list <em>yet</em>.

Comments

No comments yet. Be the first to comment!
Your email address will be verified before your first comment is posted. It will not be displayed publicly.
Legal Information
By commenting, you agree to our Privacy Policy and Terms of Service.