【发布时间】:2012-04-30 14:06:42
【问题描述】:
通过Michael Hartl's Rails Tutorial 2nd Ed Chapter 10 Exercise 5 工作,我遇到了部分和集合的问题,并且在部分中使用了部分。
第 10 章,练习 5 指出: “使用部分,消除清单 10.46 和清单 10.47 中删除链接中的重复。”
清单 10.46:app/views/microposts/_micropost.html.erb
<li>
<span class="content"><%= micropost.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
</span>
<% if current_user?(micropost.user) %>
<%= link_to "delete", micropost, method: :delete,
confirm: "You sure?",
title: micropost.content %>
<% end %>
</li>
清单 10.47:app/views/shared/_feed_item.html.erb
<li id="<%= feed_item.id %>">
<%= link_to gravatar_for(feed_item.user), feed_item.user %>
<span class="user">
<%= link_to feed_item.user.name, feed_item.user %>
</span>
<span class="content"><%= feed_item.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(feed_item.created_at) %> ago.
</span>
<% if current_user?(feed_item.user) %>
<%= link_to "delete", feed_item, method: :delete,
confirm: "You sure?",
title: feed_item.content %>
<% end %>
</li>
我的方法是创建这个文件 shared/_item_delete_link.html.erb
<%= link_to "delete", item, method: :delete,
confirm: "You sure?",
title: item.content %>
然后像这样在原始部分中使用这个部分:
清单 10.46:app/views/microposts/_micropost.html.erb
<li>
<span class="content"><%= micropost.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
</span>
<% if current_user?(micropost.user) %>
<%= render partial: 'shared/item_delete_link', collection: @microposts, as: :item %>
<% end %>
</li>
清单 10.47:app/views/shared/_feed_item.html.erb
<li id="<%= feed_item.id %>">
<%= link_to gravatar_for(feed_item.user), feed_item.user %>
<span class="user">
<%= link_to feed_item.user.name, feed_item.user %>
</span>
<span class="content"><%= feed_item.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(feed_item.created_at) %> ago.
</span>
<% if current_user?(feed_item.user) %>
<%= render partial: 'shared/item_delete_link', collection: @feed_items, as: :item %>
<% end %>
</li>
这让我的所有测试都通过了,所以我认为它可以正常工作,直到我在浏览器中检查它: http://grab.by/daUk
正在为每个 _item_delete_link 部分再次呈现整个集合,而我想要的是传递父部分中使用的原始集合中的局部变量。
我尝试使用locals: { } 和object: 选项进行渲染,但没有成功。
有人知道答案吗?谢谢!
【问题讨论】:
-
啊,刚刚想通了:
<%= render partial: 'shared/item_delete_link', locals: { item: micropost } %>和<%= render partial: 'shared/item_delete_link', locals: { item: feed_item } %>.... 有道理,只需要让当地人通过...我之前尝试过,但item: @feed_item和 @ 987654333@,但我需要传递局部变量,而不是对象。呵呵 -
请使用
locals:显示确切的代码。谢谢
标签: ruby-on-rails-3 collections partials railstutorial.org