我的类别数量未知。
我想从每个类别中选择一个帖子,当我没有其他类别时,我想从头开始,直到我达到固定数量的帖子。
这就是我所拥有的,在获得所需数量的帖子之前,我怎么能重新运行这个迭代?
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
答案 0 :(得分:1)
就个人而言,我更喜欢这样的事情:
posts = categories.cycle.take(desired_amount).each_with_index.map do |cat,ind|
cat.posts.order(position: :asc)[ind / categories.count]
end
这将为您提供每个类别中的第一篇帖子,然后是每个类别中的第二篇文章等,直到您有所需的帖子数量。需要注意的是,如果任何类别没有足够的帖子,你的最终阵列中会有一些空白点(即nils)。
答案 1 :(得分:0)
也许尝试这样的事情?
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
答案 2 :(得分:0)
你可以在开始循环之前定义一个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