【问题标题】:Rails - How to reference the current and next record togetherRails - 如何同时引用当前和下一条记录
【发布时间】:2016-10-29 12:09:41
【问题描述】:
如何循环遍历一个记录集并传递当前记录 record1 并且仍然能够在同一操作中引用下一条记录?
<% menu_item.children.menu.each do |record1| %>
<%= wrap_submenu(record1) %>
<%= wrap_submenu_a(record2) %>
<% end %>
我正在使用祖先宝石
【问题讨论】:
标签:
ruby
ruby-on-rails-4
ancestry
【解决方案1】:
你可以使用 each_cons(2) :
(1..10).each_cons(2){|a,b| puts a;puts b; puts "----"}
=>
1
2
----
2
3
----
3
4
----
4
5
----
5
6
----
6
7
----
7
8
----
8
9
----
9
10
----
所以在你的情况下:
menu_item.children.menu.each_cons(2) do |record1,record2|
...
【解决方案2】:
不是很干净,但您可以使用 each_with_index 考虑最后一个元素迭代