在包含数组的 Rails 中呈现异构对象列表

Posted

技术标签:

【中文标题】在包含数组的 Rails 中呈现异构对象列表【英文标题】:Rendering a heterogeneous list of objects in rails that includes arrays 【发布时间】:2013-07-25 19:00:21 【问题描述】:

我有一个附件、注释和附件数组的集合。例如

@heteroCollection = [Attachment, Note, Note, [Attachment, Attachment, Attachment]]

在我看来,我试图渲染这个集合

<%= render :partial => @heteroCollection %>

但是 rails 说附件数组需要实现 :to_partial_path

[Attachment, ..., Attachment] is not an ActiveModel-compatible object. It must implement :to_partial_path

如果我删除数组,渲染效果很好,分别调用 _attachment.html.erb_note.html.erb 为各自的记录。

有没有办法在没有猴子补丁的情况下在 Array 上实现 :to_partial_path?还是有其他更好的解决方案?

【问题讨论】:

【参考方案1】:

您可以创建 AttachmentArray 类,从 Array 扩展它并向其添加 to_partial_path 方法。比将您的附件推送到该类的新实例..

【讨论】:

好主意!我会试一试。

以上是关于在包含数组的 Rails 中呈现异构对象列表的主要内容,如果未能解决你的问题,请参考以下文章