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

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 %>

Solution 1:

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.

Solution 2:

I was struggling with this too. This is the method I ended up using:

<%= render :partial => "#{dynamic_partial}" rescue nil %>

Basically, if the partial doesn't exist, do nothing. Did you want to print something if the partial is missing, though?

Edit 1: Oh, I fail at reading comprehension. You did say that you wanted to render something else. In that case, how about this?

<%= render :partial => "#{dynamic_partial}" rescue render :partial => 'partial_that_actually_exists' %>

or

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

Edit 2:

Alternative: Checking for existence of the partial file:

<%= render :partial => "#{dynamic_partial}" if File.exists?(Rails.root.join("app", "views", params[:controller], "_#{dynamic_partial}.html.erb")) %>