Senator Senator - 7 months ago 60
Ruby Question

How to loop through Rails Bootstrap Carousel data slides for unknown # of slides?

I've created a working Ruby on Rails Bootstrap Carousel for my rails project with a set # of images, but my website will have a variable amount of images based on user input and I want the # of slides to vary based on that # of images. I'm new to ruby so I can't quite figure out the loop code needed to make this work... thanks for looking!

This is what the code looks like for a set # of slides (4):

<ol class="carousel-indicators">
<li data-target="#mycarousel" data-slide-to="0" class="active"></li>
<li data-target="#mycarousel" data-slide-to="1" class="active"></li>
<li data-target="#mycarousel" data-slide-to="2" class="active"></li>
<li data-target="#mycarousel" data-slide-to="3" class="active"></li>
</ol>


This is my attempt at a loop based on a count of my 'outing' model (there is one image per outing which I want to loop through). I"ll never know how many slides I'll need, one day it could be 5, next day could be 20, and day after back down to 4.

<ol class="carousel-indicators">
<li data-target="#mycarousel" data-slide-to="0" class="active"></li>
<%= x = @outings.count, for outingimagecount in 1..x do %>
<li data-target="#mycarousel" data-slide-to=#{outingimagecount)></li>
<% end %>
</ol>

Answer

Try each-with-index:

<% @outings.each_with_index do |outing, i| %>
  <li data-target="#mycarousel" data-slide-to=#{i) class="#{'active' if i == 0}"></li>
<% end %>

Or you could do:

<% (1..@outings.count).each do |i| %>
Comments