.each_with_index
appends the index
variable:
%w(cat dog wombat).each_with_index {|item, index|
hash[item] = index
}
hash #=> {"cat"=>0, "dog"=>1, "wombat"=>2}
In your example:
<% @child.toys.attributes.each_with_index do |key,value,index| %>
<%= key %>
<%= value %>
<%= index %>
<% end %>
Toys needs to be a member object (attributes won't work on a collection).
-
I also tested with just declaring "key", as follows:
<% @child.toys.attributes.each_with_index do |attr,index| %>
<%= attr[0] %>
<%= attr[1] %>
<%= index %>
<% end %>
attr
is returned as an array in this instance, where the key/value is used as 0
and 1
elements of the array respectively.