robb
robb

Reputation: 294

Rails loop not generationg grids

I have a loop that iterates through a list of stories but it's generating one row per story and not 3 columns. What am I missing?

<div class="row">
    <div class="col-md-4">
        <% @stories.each do |story| %>
        <h2><%= story.name.titleize %></h2>
        <%= image_tag story.pictures.first.image(:medium).to_s, class: "img-responsive" %>
        <%= link_to "View Story", story_path(story) %>
        <% end %>
    </div>
</div>

Thanks.

Upvotes: 0

Views: 132

Answers (2)

jpheos
jpheos

Reputation: 458

Take a look to each_slice

@stories = [story1, story2, story3, story4, story5, story6, story7, story8]
@stories.each_slice(3).to_a
#=> [[story1, story2, story3], [story4, story5, story6], [story7, story8]]

I think you can try this:

<% @stories.each_slice(3).to_a.each do |row_stories| %>
    <div class="row">
        <% row_stories.each do |story| %>
            <div class="col-md-4">
            <%= content_tag :h2, story.name.titleize %>
                <%= image_tag story.pictures.first.image(:medium).to_s, class: "img-responsive" %>
                <%= link_to "View Story", story_path(story) %>
                </div>
        <% end %>
    </div>
<% end %>

Upvotes: 1

DaniG2k
DaniG2k

Reputation: 4893

I think you're placing the each loop in the wrong place. Try something like:

<div class="row">
  <% @stories.each do |story| %>
    <div class="col-md-4">
      <%= content_tag :h2, story.name.titleize %>
      <%= image_tag story.pictures.first.image(:medium).to_s, class: "img-responsive" %>
      <%= link_to "View Story", story_path(story) %>
    </div>
  <% end %>
</div>

Upvotes: 1

Related Questions