Is there any Rails function to check if a partial exists?

Daniel Cukier picture Daniel Cukier · Aug 24, 2010 · Viewed 31k times · Source

When I render a partial which does not exists, I get an Exception. I'd like to check if a partial exists before rendering it and in case it doesn't exist, I'll render something else. I did the following code in my .erb file, but I think there should be a better way to do this:

    <% begin %>
      <%= render :partial => "#{dynamic_partial}" %>
    <% rescue ActionView::MissingTemplate %>
      Can't show this data!
    <% end %>

Answer

Rein picture Rein · Nov 18, 2011

Currently, I'm using the following in my Rails 3/3.1 projects:

lookup_context.find_all('posts/_form').any?

The advantage over other solutions I've seen is that this will look in all view paths instead of just your rails root. This is important to me as I have a lot of rails engines.

This also works in Rails 4.