首页 > 解决方案 > Rendering collections within collection in Rails

问题描述

This is driving me crazy, I thought it should be something very simple but I've spent all day trying to figure it out and getting nowhere. I've looked all over, there's something I must be missing.

I want to render a partial for a collection, within a partial from a collection.

Eg. I have a collection of entries which I want to render in my feed partial, I want feed to come from a collection of feeds, such that the page displays all entries in all feeds.

How can I do this?

Something like:

controller:

@feeds = Feeds.all

allmyfeeds.html.erb

@feeds.each do |feed|
<%= render 'feed' %>
<% end %>

or

<%= render 'feeds', collection: @feeds %>

_feed.html.erb

<%= render 'items', collection: @items %>

_item.html.erb

<%= item.summary.html_safe %>

But I really don't know.

标签: ruby-on-rails

解决方案


Partial naming conventions will really help you out here...

In allmyfeeds.html.erb (which i'm guessing is actually feeds/index.html.erb), instead of this...

@feeds.each do |feed|
  <%= render 'feed' %>
<% end %>

You can simply call this...

<%= render @feeds %>  # this will invoke _feed.html.erb for every feed in the collection, automatically

Inside your _feed.html.erb partial...

# Note: You may need to change `items` to something like `items/items` if it is not located in the same directory
<%= render partial: 'items', locals: { items: feed.items } %>

Then in your items partial, you will have access to items, which is a collection of items for that particular feed


推荐阅读