Search code examples
ruby-on-railspartial

Rails: Rendering a Superclass Partial


I have two classes (Impressions and Replies) which inherit from the parent class Comment:

class CommentsController < ApplicationController
  . . . .
end

class ImpressionsController < CommentsController
  . . . .
end

class RepliesController < CommentsController
  . . . .
end

In my view, I want them to render the same way. Right now, I'm approaching it like this:

<%= render @comment %>

Ideally, this would render the partial "/comments/_comment", but instead Rails want to render things like "/impressions/_impression" or "/replies/_replies." Is there any way to strong arm Rails into do "/comments/_comment"?


Solution

  • With :collection you can render a collection of objects. Given a single object you should us :object instead.

    <%= render partial: '/comments/comment', object: @impression %>
    

    The :as is not necessary as long as the partial is named 'comment'. If you name your partial e.g. 'my_comment' then @impression would be accessible via the local variable 'my_comment' and you would have to use :as to define a different local name.

    However in your case I would prefer to define a partial path for the Impression and Replies model as follows (Rails >3.2.?):

    class Impression < ActiveRecord::Base
      ...  
    
      def to_partial_path
        "comments/comment"
      end
    end
    

    Then you can use the standard rendering with an object or collection

    <%= render @comment %>