[英]Rails: Rendering a Superclass Partial
I have two classes (Impressions and Replies) which inherit from the parent class Comment:我有两个从父类 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."理想情况下,这将呈现部分“/comments/_comment”,但 Rails 想要呈现诸如“/impressions/_impression”或“/replies/_replies”之类的内容。 Is there any way to strong arm Rails into do "/comments/_comment"?
有什么办法可以让强大的 Rails 做“/comments/_comment”?
I think smth like this can help:我认为这样的事情可以提供帮助:
<%= render :partial => '/comments/comment', :collection => @impressions,
:as => :comment %>
With :collection you can render a collection of objects.使用 :collection 可以渲染对象的集合。 Given a single object you should us :object instead.
给定一个对象,你应该使用 :object 代替。
<%= render partial: '/comments/comment', object: @impression %>
The :as is not necessary as long as the partial is named 'comment'.只要部分名为“评论”,就不需要 :as 。 If you name your partial eg '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.
如果您将部分命名为例如“my_comment”,则可以通过局部变量“my_comment”访问@impression,并且您必须使用 :as 来定义不同的本地名称。
However in your case I would prefer to define a partial path for the Impression and Replies model as follows (Rails >3.2.?):但是,在您的情况下,我更愿意为印象和回复模型定义部分路径,如下所示(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 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.