Rails:渲染超类部分

时间:2012-11-29 03:06:31

标签: ruby-on-rails partial

我有两个类(Impressions and Replies)继承自父类Comment:

class CommentsController < ApplicationController
  . . . .
end

class ImpressionsController < CommentsController
  . . . .
end

class RepliesController < CommentsController
  . . . .
end

在我看来,我希望它们以同样的方式呈现。现在,我正在接近它:

<%= render @comment %>

理想情况下,这会呈现部分“/ comments / _comment”,而Rails想要呈现“/ impressions / _impression”或“/ replies / _replies”之类的内容。有没有办法让强壮的Rails进行“/ comments / _comment”?

2 个答案:

答案 0 :(得分:1)

我觉得这样的事情会有所帮助:

<%= render :partial => '/comments/comment', :collection => @impressions,
           :as => :comment %>

答案 1 :(得分:1)

使用:collection可以渲染对象集合。给定一个对象,你应该对我们:对象。

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

:只要部分被命名为“评论”,就没有必要。如果您将部分命名为'my_comment'然后可以通过局部变量'my_comment'访问@impression,你必须使用:as来定义一个不同的本地名称。

但是在您的情况下,我更愿意为Impression and Replies模型定义部分路径,如下所示(Rails&gt; 3.2。?):

class Impression < ActiveRecord::Base
  ...  

  def to_partial_path
    "comments/comment"
  end
end

然后,您可以将标准渲染与对象或集合

一起使用
<%= render @comment %>