轨道 - 如何将一些数据放入循环轨道中



我想在我的循环中放一些数据。

示例:我有 10 个帖子。我想在这些帖子中为每 1 个帖子放置 3 个数据。

  1. 帖子 1
  2. 帖子 2
  3. 帖子 3
  4. 数据 1
  5. 帖子 4
  6. 帖子 5
  7. 帖子 6
  8. 数据 2
  9. 帖子 7
  10. 帖子 8
  11. 帖子 9
  12. 数据 3

我的代码 :

帖子索引:

<%= render @posts %>

_post.html.erb

<div class="col-lg-12">
<h1><%= post.title %></h1>
<p><%= post.body %></p>
</div>

怎么做?谢谢你帮助我..

Rails 会自动为您的集合部分提供一个名为 name_of_model_counter 的计数器(在您的例子中为post_counter)。因此,仅当计数器为某个数字时,您可以使用它来插入数据。即将此添加到您的部分的底部...

...
<% if post_counter % 3 == 0 %>
<div class="col-lg-12">
# insert data here
</div>
<% end %>

您可以在div 中使用 case 语句(或类似语句)来确定post_counter的确切值,以便为每个语句呈现不同的数据。

重要的部分是post_counter存在,可用于检查您正在使用哪个迭代。

编辑评论问题:假设你会提前知道有多少数据,你可以添加另一个这样的条件......

# replace x with the iteration number you want to stop at
<% if (post_counter <= x) && (post_counter % 3 == 0) %>

最新更新