Rails: for every 3 records
I am currently studying rails. I am trying to understand the following:
<% @obj.{For each 3 records} do |records| %>
<%end %>
How would you implement this "for every 3 records"?
What am I trying to do? I would like to display data in 3 columns. So I am using a table. Each record represents table data ( <td><td>
). After every 3 entries, I will need to type a <tr></tr>
.
Many thanks for your help
source to share
You can use each_slice
and pass 3 as an argument:
<% @obj.each_slice(3) do |records| %>
<%= records %> <!-- your code -->
<% end %>
You can add what you need to print at the end of each group, for example:
[1,2,3,4,5,6,7,8,9].each_slice(3) do |element|
puts "#{element} group end"
end
# "[1, 2, 3] group end"
# "[4, 5, 6] group end"
# "[7, 8, 9] group end"
source to share
You can use in_groups_of on an array like:
[1 2 3 4 5 6 7 8 9 10].in_groups_of(3, false) do |group|
puts group
end
# [1, 2, 3]
# [4, 5, 6]
# [7, 8, 9]
# [10]
source to share
I think you are looking for find_in_batches or possibly in_batches .
In your controller, you can do something like:
@foos = Foo.where(some: :condition)
Then, in your opinion:
<% @foos.in_batches(of: 3) do |foos_relation| %>
... do something with your relation of three foos
<% end %>
source to share