Have Rails Partials Pull Data Directly For DRY Code and Easy Testability

Published May 23, 2017

Rails Partials are often reused on multiple pages, so why not have them pull their required data directly instead of repeating code in multiple controllers that pushes data to them!?

Example:
HomePageController might be rendering _bookings.html.erb, _locations.html.erb, and _providers.html.erb, thus having code like this in its index action:

@bookings = Booking.all
@locations = Location.all
@providers = Provider.all

And then BookingsController repeating:

@bookings = Booking.all

LocationsController repeating:

@locations = Location.all

ProvidersController repeating:

@providers = Provider.all

An alternative is to add the following to ApplicationHelper:

def bookings
  @bookings ||= Booking.all
end
def locations
  @locations ||= Location.all
end
def providers
  @providers ||= Provider.all
end

Include in ApplicationController.

Delete all lines setting up these variables in all controllers, HomePageController, BookingsController, LocationsController, and ProvidersController

And finally only call "bookings", "locations", and "providers" from their respective partials.

That is DRY Rails variable setup code for the win. Makes it easy to test-drive the partial views too!

Discover and read more posts from Andy Maleh
get started
Enjoy this post?

Leave a like and comment for Andy