重申 collection

Reiterate over collection

我有未知数量的类别。

我想从每个类别中选择一个post,当没有更多类别时我想从头开始,直到达到固定数量post。

这就是我所拥有的,我如何才能重新运行此迭代直到获得我想要的 post 数量?

desired_amount = 40
categories.each_with_index do |category, index|
  post = category.posts.order(position: :asc)[index]
  # do something with the post
  return if desired_amount == (index + 1)
end

也许试试这样的方法?

all_posts = []
#include posts to prevent constant querying the db
categories_with_posts = categories.includes(:posts)

until all_posts.size == 40
 categories_with_posts.each do |category|
   #pick a random post from current category posts
   post = category.posts.order(position: :asc).sample

   # add the post to collection if post is not nil
   all_posts << post if post

   # do something with the post
   break if all_posts.size == 40
 end
end

您可以在开始循环之前定义一个 post 的数组:

desired_amount = 40
posts_array = []
unless posts_array.count == desired_amount 
  categories.each_with_index do |category, index|
    post = category.posts.order(position: :asc)[index]
    posts_array << post
    return if desired_amount == (index + 1)
  end
end

就个人而言,我更喜欢这样的东西:

posts = categories.cycle.take(desired_amount).each_with_index.map do |cat,ind|
  cat.posts.order(position: :asc)[ind / categories.count]
end

这将为您提供每个类别中的第一个 post,然后是每个类别中的第二个 post,依此类推,直到您获得想要的 post 个数。一个警告是,如果任何类别没有足够的 posts,您的最终数组中将有一些空点(即 nils)。