ruby-on-rails - 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.
解决方案
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
推荐阅读
- c# - #if Debug 如果不调试,则不会禁用按钮
- php - 在 Unity 中支持 html 标签
- python - 使用 python mindom 读取具有不同编码的 XML
- django - Django 密码 help_text 无法正确呈现
- python - 尝试根据类型计算每行的百分比排名(这是一个包含大约 10 个 unqiue 字符串的列)
- tsql - FreeTDS TSQL 不适用于 freetds.conf
- r - R:叠加轨迹图和散点图
- apache-kafka - 卡夫卡坚持消息,直到被所有组消费
- java - selenium java尝试通过vpn访问数据库
- javascript - MFF 8.0 调用过程参考错误