Rails: Render collection partial: Getting size of collection inside partial
Ah. Wanted to answer the question. But found correct answer. Anyway here is a tip on future. You can investigate the Rails mechanism with Ruby metaprogramming. For example by calling method 'Kernel#local_variables' in a view which in my case outputs:
[0] = :local_assigns
[1] = :output_buffer
[2] = :row
[3] = :row_counter
[4] = :row_iteration
[5] = :highlighted_description
[6] = :source_description
in case of
<%= render partial: 'card', collection: @offers, as: :row %>
The following is possible since Rails Version 4.2:
Inside the partial you have access to a function/variable called collection_iteration
. Calling collection_iteration.size
will give you the total.
From the changelog:
The iteration object is available as the local variable
#{template_name}_iteration
when rendering partials with collections.It gives access to the
size
of the collection being iterated over, the currentindex
and two convenience methodsfirst?
andlast?
.