【问题标题】:Rails rendering a partial multiple times based on the collection sizeRails 根据集合大小多次渲染部分
【发布时间】:2011-01-30 17:22:26
【问题描述】:

我有一个带集合的部分,遍历该集合以显示各个项目。

代码如下:

部分:

<% for point in @points %>
<div id="im" style="float:left;width:80px;height:90px;padding:5px;border:solid 1px #D3D3D3; margin:5px; ">
    <img width="80" height="80" src="\uploaded\<%= point.id %>.gif" />
    <%= link_to_remote "&nbsp;&nbsp;&nbsp;Delete", :url => { :action => "delete_point", :id => point.id  }, :before => "Element.show('spinner')",  :complete => "Element.hide('spinner')" %>        
</div>
<% end %>

来自控制器的 rjs:

page.replace_html :points_partial, :partial => 'points', :collection=>@points

由于某种原因,部分是由集合中的项目数量呈现的。如果集合中有 10 个项目,则部分渲染然后次。

这家伙也有类似的问题,但与布局有关。

Render partial in Ruby on rails a collection is multiplying items

这让我发疯了,因为它应该很简单,并且所有其他部分都可以毫无困难地工作。

【问题讨论】:

    标签: ruby-on-rails ruby partial renderpartial


    【解决方案1】:

    :collection 导致控制器迭代 @points 并为集合中的每个项目渲染一次部分。如果您将部分设置为仅渲染一个点,则控制器代码应按预期工作。

    顺便说一句,在 Rails 3 中,您可以使用 &lt;%= render @points %&gt; 作为 &lt;%= render :partial =&gt; "points/point", :collection =&gt; @points %&gt; 的快捷方式

    【讨论】:

    • 我会选择不同的观点,可能是这样的:if @points.nil? render :action =&gt; "index" end
    • 你的partial的名字必须是_point.html.erb,并且它必须驻留在points/中
    • 或者 .... 你可以使用 :object => @points 将数组传递到部分 .... 或者。
    【解决方案2】:

    :collection 参数告诉部分“显示@points 的每个成员的部分”,然后您的部分再次遍历同一个集合。

    在您的部分中,只需摆脱包装 for point in @points 循环,它应该可以正常工作。

    查看这里了解更多信息:http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-collections

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2015-10-22
      • 1970-01-01
      • 2016-04-24
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多