限制代码块中的输出数量,Rails

Limiting the number of outputs in a code block, Rails

我的帖子索引视图中有这段代码:

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

每个 post 可能有 5 个以上的练习与之关联,但我只想在索引页面上为每个 post 显示 5 个。我不知道如何限制每个 post 的数量。我已经在块“@exercises.limit(5).each”的开头尝试了限制功能,但这只存在前 5 个练习。控制器中的实例变量如下所示:

@exercises = Exercise.all

更新: 这是我的模型:

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

在我看来没有任何其他相关代码,在我的控制器中也不多:

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

* 基于 Post has_many exercisesExercise belongs_to post 的假设。 *

在您的 Exercise 模型的 class 中添加以下方法:

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

对于特定的 post.

,此方法将仅检索 5 exercises

然后,在你的 PostsController:

@exersises_to_display_for_post = Exercise.exercises_to_display_for_post(@post)

然后,您可以在 view 中使用 @exersises_to_display_for_post 实例变量,其中恰好有 5 个 exercises 对应于 @post!

在您看来,您可以访问 @post 实例变量,它对应于 @exersises_to_display_for_post 实例变量中的 5 exercises。现在,您只需要遍历它们并显示!