سؤال

I have two different loops that I use on the same view of my rails app, I know how to limit the output for one of them, eg .take(6), .limit(6) etc, but my problem is that because two loops that loop the same variable but in different ways, the limit on one them (and everything else i seemed to try) limits the output of both of the loops and not each one individually. for instance, when I have .take(6), instead of taking the 6 from each different loop it takes 6 together from both loops. It might be clearer with my code:

<% @steppy = Steppy.order('created_at DESC')%>

<% @steppy.limit(6).each do |steppy| %>

    <% if steppy.goal.present? %>
        <%= link_to steppy do%>
            <div>       
                <div>
                    <li class="front_panel_new" style="list-style-type: square;">How to become <%= steppy.goal.indefinite_article %> <%= truncate(steppy.goal.capitalize, :length => 150) %></li>
                </div>
            </div>
        <% end %>  
    <% end %>
<% end %>
<% @steppy.each do |steppy| %>
  <% if steppy.ask.present? %>

          <div>       
              <div>
                <%= link_to steppy do%>
                  <li class="front_panel_new" style="list-style-type: square;">How to become  <%= steppy.ask.indefinite_article %>  <%= truncate(steppy.ask.capitalize, :length => 150) %></li>
                <% end %> 
              </div>
          </div>

  <% end %>
<% end %>

I need them to have their own separate limit of 6 each.

هل كانت مفيدة؟

المحلول

You have a logic problem here, see this code:

# controller
@steppies_having_ask = Steppy.where("ask IS NOT NULL AND ask != ''").order('created_at DESC').limit(6)
@steppies_having_goal = Steppy.where('goal IS NOT NULL AND goal != ''').order('created_at DESC').limit(6)

# view
@steppies_having_goal.each do |steppy|
  # display your steppy without testing `if steppy.goal.present?`
end

@steppies_having_ask.each do |steppy|
  # display your steppy without testing `if steppy.ask.present?`    
end

What is the logic problem you have?

  • You get 6 records from the DB and loop on it,
  • Then you display the record only if it has a value for the ask attribute (or goal)

What if the 6 records have no value for ask (or goal)? -> It would display nothing.

نصائح أخرى

Works ok for me. Try using take instead of limit perhaps?

steppy = [1,2,3,4,5,6,7,8,9,0]
steppy.take(2).each do |s|
   puts "first loop #{s}"
end

steppy.take(6).each do |s|
   puts "second loop #{s}"
end

Produces

first loop 1
first loop 2
second loop 1
second loop 2
second loop 3
second loop 4
second loop 5
second loop 6

.each_slice(x) is good too, except it won't fix your problem (just provide blocks for the same var):

steppy.each_slice(6) do |block|
    for item in block do
       # outputs each item
    end
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top