Adding a partial in Rails

By | 11/09/2015

Sometimes you just need to repeat the same code across the site and whilst it’s great to have it in the application.html.erb file it can make it look a little messy… that’s where partials come in.

A partial is basically a part of your code you want to reuse and here’s how to do it. Not sure if this is exactly best practice but it’s how I like to do it.

I create a new folder in my views folder called ‘shared’
In that folder I then crate a new file with a name that indicates the code I’m reusing, in this example I’m putting the navigation menu code in there so _partial_nav.html.erb.

One thing to note about the partial filename is it MUST start with an underscore (_).

Once you’ve done this head back to the file you extracted the code from in your partial and use the following to insert:

<%= render partial: 'shared/partial_nav' %>
N.B. you don't include the underscore when referencing the file.

And that's how you insert a partial