Search code examples
ruby-on-railsvariableslimitcodeblocks

Limiting the number of outputs in a code block, Rails


I have this piece of code in my Posts index view:

<% @exercises.each do |exercise| %>
    <% if exercise.post_id == post.id %>
        <table>
            <tr>
                <th style="color:white;"><%= exercise.name %></th>
            </tr>
        </table>
    <% end %>
<% end %>

Each post has potentially 5+ exercises associated with it, but I want to only display 5 for each post on the index page. I can't figure out how to limit the number for each post. I've tried the limit function at the beginning of the block '@exercises.limit(5).each' but that only does the first 5 exercises that exist. The instance variable in the controller looks like:

@exercises = Exercise.all

UPDATE: Here are my models:

class Exercise < ActiveRecord::Base
    belongs_to :post
    belongs_to :user
    belongs_to :extype  
end

class Post < ActiveRecord::Base
    searchkick
    belongs_to :user
    belongs_to :category
    has_many :comments
    has_many :exercises

    accepts_nested_attributes_for :exercises
end

There isn't any other relevant code in my view, and not much in my controller:

def index

    @exercises = Exercise.all


    if params[:category].blank?
        @posts = Post.all.order("created_at DESC")
    else
        @category_id = Category.find_by(name: params[:category]).id
        @posts = Post.where(:category_id => @category_id).order("created_at DESC")
    end
end

Solution

  • * Based on assumption that, Post has_many exercises and Exercise belongs_to post. *

    Add the following method in your Exercise Model's class:

       def self.exercises_to_display_for_post(post)
          Exercise.where(post_id: post.id).limit(5)
       end
    

    This method will retrieve only 5 exercises for a particular post.

    Then, in your PostsController:

    @exersises_to_display_for_post = Exercise.exercises_to_display_for_post(@post)
    

    Then, you can use @exersises_to_display_for_post instance variable in your view where you have exactly 5 exercises corresponding to that @post!

    In your view, you have access to @post instance variable and it's corresponding 5 exercises in the @exersises_to_display_for_post instance variable. Now, you just need to loop through them and show!