Posts tagged locals

Partials Should Never Contain Instance Variables

It may seem that the benefits of partials in our Rails application are endless. They help keep our views DRY, organized, and easily reusable. But with great power comes great responsibility.

Due to the flexibility partials give us, controlling the data flow to partials should not be an oversight. Let’s say we’re using one partial in two separate views which will render a message on the page:

Since @message in used in the partial, we must define the variable in both the Dashboard and Photo controllers. If we want to change @message to another name in one of our controller actions, then all other instances of @message must be renamed as well. For this reason, our partial becomes difficult to reuse and manage.

To combat against an issue like this we can use local variables:

You’ll notice just after the file name, we are adding an additional option which is our local variable. We can now set message to whatever we want, and then use the message local variable within our partial.

This method now allows us to use the partial freely across all our views without the worry of having to trace our variables back to multiple controllers.

For situations where you may have more than one local that needs to be passed along to a partial, just use the locals hash locals: { }.

So next time you find yourself working with partials, remember, a good practice when passing data to your partials is to use locals over instance variables.

For more best practices about rendering partials, the Layouts and Rendering section in Rails Guides is a great starting point.

(Visited 11 times, 1 visits today)