Daði Hall Daði Hall - 5 months ago 13
Ruby Question

Adding each_slice (3) gives Error in Rails App

I'm working on this

do
loop in my app, it works fine but I want to take it further (see below) and I'm not sure how to do that.

<div class="row">

<% @products.each do |category, products| %>
<% products.each_with_index do |product, index| %>
<% if index == 0 %>
<div class="col-lg-4 col-sm-6 col-xs-12 center-block " >

<%= image_tag product.image.url(:medium), class: "img-responsive" %>
<div class="caption">
<p><%= product.category.name %></p>
</div>
<% end %>
</div>
<% end %>
<% end %>

</div>


At the moment the loop is looping through 12 categories and displaying one image from each category. I don't want to have all the images appearing in the same row.

I tried to add
each_slice(3)
to the loop but it gives me this error:


undefined method 'image' for 5:Fixnum


This is how the code looks after the
each_slice(3)
insertion

<% @products.each_slice(3) do |category, products| %>
<div class="row">
<% products.each_with_index do |product, index| %>
<% if index == 0 %>
<div class="col-lg-4 col-sm-6 col-xs-12 center-block " >

<%= image_tag product.image.url(:medium), class: "img-responsive" %>
<div class="caption">
<p><%= product.category.name %></p>
</div>
<% end %>
</div>
<% end %>
<% end %>

</div>


I'm not sure what to do here or if each_slice (3) is the right way to do this.

Answer

array = [..]

array.each_slice(x) will give you array.size / x arrays different.

Example :

> [1,2,3,4,5,6].each_slice(2) do |g| p g end
[1, 2]
[3, 4]
[5, 6]

So you have to add a loop to your code :

<% @products.each_slice(3) do |products_group| %>
   <% products_group.each do |category, products| %>
   ...
   <% end %>
<%end%>
Comments