我有一个Rails'actionview部分,它遍历层次结构中的对象 - 分支对象(模拟数组)包含叶子或分支对象等。对于每个分支对象,我有部分代码:
branch.each do |child|
render partial: child.class.to_s.underscore, object: child, layout: child.layout
end
输出是明智的:
[#<LeafObject:0x007fbf6806f480 @id="obj1">, #<LeafObject:0x007fbf700c80c8 @id="obj2">]
考虑到那些叶子对象的部分包含<%= leaf_object.id %><br />
,我希望得到以下结果:
obj1<br />obj2<br />
这就是它变得奇怪的地方。如果我直接在分支数组中的对象上调用render
,它只能在我单独执行时才能工作。似乎第一个对象的缓冲区被第二个对象覆盖。
render partial: branch[0].class.to_s.underscore, object: branch[0], layout: branch[0].layout
render partial: branch[1].class.to_s.underscore, object: branch[1], layout: branch[1].layout
...可生产
obj2<br />
是的,我知道:WTF!?!这就像渲染在枚举器中的行为方式不同。
另外,请记住我没有使用集合,因为每个对象的布局都会发生变化(即branch [0] .layout)。使用集合可以工作,但不能按对象布局使用。
知道我做错了什么吗?多次调用渲染是一件坏事吗?任何人都会感激不尽。
版本:Ruby:1.9.3,Rails:3.2.10
答案 0 :(得分:0)
只是检查,但你是否留下了一些ERB标签?
<% branch.each do |child| %>
<%= render partial: child.class.to_s.underscore, object: child, layout: child.layout %>
<% end %>
因为输出错误:
[#<LeafObject:0x007fbf6806f480 @id="obj1">, #<LeafObject:0x007fbf700c80c8 @id="obj2">]
表明你实际上在做类似的事情:
<%= branch %>