Search code examples
ruby-on-railsviewcollectionspathpartial

nicer paths to partial views of subclasses when rendering a collection


Suppose I have:

class Edible
end
class Apple < Edible
end
class Orange < Edible
end

I am rendering a collection of these edibles, regardless of their actual type:

<%= render @edibles %>

This works, but Rails wants me to place these views in apples/apple and oranges/orange.

Is there a way to tell Rails to look for views in the same folder, i.e. edibles/apple and edibles/orange?


Solution

  •   def partial
        edible_type.class.name.underscore ##edible type can be apple or orange
      end
    
    <% @edibles.each do |edible| %>
      <%= render( :partial => "edibles/#{edible.partial}", :locals => {:edible => edible}) %>
    <% end %>