Partial Views in Rails: Keeping it DRY!

October 30, 2015 By 0 Comments

Next up is being able to render partials in a view. In short, a lump of display logic can be separated out from the view and reused as required. This may be useful for pages that repeat a particular element. For example, you may want to have a rotating “Quick Tip!” message on multiple pages, but don’t want to copy the code onto each page’s view to do so.

Filenames should start with an underscore ( _), and end in the usual .html.erb  extension the rest of your views use.

There are two main ways of doing this, one of them creates a global partial that’s usable anywhere, as if it were local, and the other creates a local partial that can be accessed by views in the same controller. It should be noted that you can access these “local” partials by specifying a path to them (e.g. '../tasks/_partial.html.erb'), even from other controllers’ views.

In your app/views folder, create a new folder named application. In this create a new file and name it _tip.html.erb. (If you want a local partial, just create the file in your controller’s view folder instead!) This will contain your reusable code, for example:

Next, in order to display this in your views, go to your view file, and pass the location as a parameter to render:

Note that we don’t need the underscore we used in the filename, Ruby knows what we mean. But it does show us that it’s not a view that’s used directly, and will only be included as a partial view within others.

I know this example was pretty simple, but it should help.