Search code examples
rubyloopsruby-on-rails-5

Skip certain indices while iterating each and maintaining group size


I have piece of code that currently takes an array of elements (in this case blog posts), sorts their numerical ID in descending order, puts them into groupings of 3, and iterates through each and every one of them.

I need to add a condition where if blog.published is false for any blog, do not display it and use the next blog.

Whenever a blog that has the published value set to false, the grouping will set the position in the grouping to nil, rather than filling it with the next blog entry, leaving some groupings with only 2 or 1 blogs on the view. I have attempted increasing the index by replacing each with each_with_index and iterating the index value when the condition is met, but this also yields the same issue. Here is my current code.

<% @blogs.order('created_at DESC').in_groups_of(3, false).each do |group| %>
   <div class="row pt-3">
      <% group.each do |blog| %>
        <% next if blog.published == false && current_page?(root_path) %>
           <%# Do View Stuff For Each Blog Here %>
      <% end #each %>
   </div>
<% end #grouping %>

Each grouping should always have 3 blogs and should skip over any blog that has the publication value set to false.


Solution

  • @blogs = Blog.where.not(published: false).order('created_at desc').in_groups_of(3, false)

    PS. If you're doing @blogs = Blog.all in your controller, try not to build AR queries inside your view. Even queries aren't executed until you call it somehow, they should be fully-built in your controller method.