Today I Learned

hashrocket A Hashrocket project

Add partial lookup prefixes in Rails

Utilizing partials in Rails can be super powerful, primarily when you use them in other templates. However, using a partial outside of its intended resource when it contains additional partials can give you a bad day.

# app/views/foos/_foo.html.erb

Foobity doo
<%= render "bar" %>
# app/views/dews/show.html.erb

Dewbie doo
<%= render "foos/foo" %>

After requesting the "dews/show" template, you'll probably find yourself with a disappointing error page saying the "bar" partial cannot be found.

Missing partial dews/_bar, application/_bar

As you can gather, partial lookup is trying to find the "bar" partial in the context it was called from. We declared the "foo" partial explicitly, so it did not error there. Since the "foo" partial calls the "bar" partial internally without being fully qualified, Rails is trying to find where it lives but cannot find it.

We can use a trick to help the template finder out. In your controller, we can define a local_prefixes method and add the prefix where the partial lives.

class DewsController < ApplicationController
  def self.local_prefixes
    super << "foos"

Rails can now find the sub-partial once you've added "foos" to the lookup context.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.