Render partial在Ruby中,rails上的集合是乘法项 [英] Render partial in Ruby on rails a collection is multiplying items
问题描述
我想在Ruby-on-Rails中显示页面中的项目列表。我在我的 index.html.erb
文件中使用partials
I want to display a list of items in a page in Ruby-on-Rails. I use partials
我有:
<%= @lista = News.find(:all, :order => Document::COL_DATE + ' DESC, id DESC')
render :partial => "newsitem",
:layout => "list_news",
:spacer_template => "spacer",
:collection => @lista
%>
在 _list_news.html.erb
:
<div class="news">
<%= yield %>
</div>
在 _spacer.html.erb
< hr />
在 _newsitem.html.erb
我有
<%= newsitem_counter + 1 %>
<!-- Code to print details for one item -->
问题是它多次打印列表:
The problem is that it prints the list multiple times:
如果列表有3个项目,它会显示它们3次:1,2,3,1,2,3,1,2,3。
如果它有7个项目,那些项目已打印7次。
If the list has 3 items, it shows them 3 times: 1,2,3,1,2,3,1,2,3.
If it has 7 items, those items are printed 7 times.
我的代码有什么问题?
推荐答案
:layout选项通常与:action或单个:partial,不与:collection集合使用。问题:正在为列表中的每个项目调用yield。
The :layout option is usually used with :action or a single :partial, not with :collection's. The problem: yield is being called for every item in the list.
您必须查看源代码来找出原因:layout和:collection办法;但足以说你的代码应该可能只是重写,以便它不依赖于:layout和:collection一起工作。
You'd have to look at the sources to figure out why :layout and :collection are acting this way; but suffice it to say your code should probably just be rewritten so that it doesn't rely on :layout and :collection working together.
这里有一种方法,假设在其他视图中重用此代码是高优先级。除非你使用大量的缓存,渲染每个部分往往是相当慢,尤其是如果你的news_feed有很多项目,所以我把它整合成一个。
Here's one way you could do so, with the assumption that reusing this code in other views is a high priority. Unless you're using lots of caching, rendering each partial tends to be fairly slow, especially if your news_feed has many items, so I've consolidated it into one.
controller / news_controller.rb
class NewsController < ApplicationController
def index
@news_feed = News.find(:all,
:order => Document::COL_DATE + ' DESC, id DESC')
end
end
views / news / index.html.erb
<%= render :partial => "news_feed",
:locals => { :news_feed => @news_feed} %>
views / news / _news_feed.html.erb
<ul class="news">
<% news_feed.each_with_index do |news_item, news_item_counter| %>
<li>
<%= newsitem_counter + 1 %>
<%# Code to print details for one item %>
</li>
<% end %>
</ul>
如果呈现一大堆分数对于运行时间来说是好的,你可能会发现这个实现 views / news / _news_feed.html.erb
更好:
If rendering a whole bunch of partials is okay for you running-time wise, you might find this implementation of views/news/_news_feed.html.erb
nicer:
<div class="news">
<%= render :partial => 'news_item', :collection => news_feed, :spacer_template => "horizontal_break" %>
</div>
views / news / _news_item.html.erb
<%= newsitem_counter + 1 %>
<%# Code to print details for one item %>
views / news / _horizontal_break.html.erb
< hr />
因此,不是渲染:layout,你渲染一个大的部分,它包装集合。
So instead of rendering :layout, you render one big partial which wraps the collection.
这篇关于Render partial在Ruby中,rails上的集合是乘法项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!