从数据库中获取每 n 条记录 - Ruby Rails

Get every n record from database - Ruby on Rails

我正在尝试制作响应式图像网格(这里是 w3schools 的示例:Responsive Image Grid)。从示例中,他们具有以下 html:

<div class="row"> 
  <div class="column">
    <img src="/w3images/wedding.jpg" style="width:100%">
    <img src="/w3images/rocks.jpg" style="width:100%">
    <img src="/w3images/falls2.jpg" style="width:100%">
    <img src="/w3images/paris.jpg" style="width:100%">
    ...
  </div>
  <div class="column">
    <img src="/w3images/underwater.jpg" style="width:100%">
    <img src="/w3images/ocean.jpg" style="width:100%">
    <img src="/w3images/wedding.jpg" style="width:100%">
    <img src="/w3images/mountainskies.jpg" style="width:100%">
    ...
  </div>  
  <div class="column">
    <img src="/w3images/wedding.jpg" style="width:100%">
    <img src="/w3images/rocks.jpg" style="width:100%">
    <img src="/w3images/falls2.jpg" style="width:100%">
    <img src="/w3images/paris.jpg" style="width:100%">
    ...
  </div>
  <div class="column">
    <img src="/w3images/underwater.jpg" style="width:100%">
    <img src="/w3images/ocean.jpg" style="width:100%">
    <img src="/w3images/wedding.jpg" style="width:100%">
    <img src="/w3images/mountainskies.jpg" style="width:100%">
    ...
  </div>
</div>

但是,他们使用的是静态内容。我想让内容动态化。我做了一些研究并找到了以下解决方案:Return every nth row from database using ActiveRecord in rails。不确定这是否是正确的方法,但我的目标是将每个 n 元素放入每个 column 中而不指定限制。

目前,我的控制器中有以下代码:

def index
  @photos = Photos.is_active.all
end

索引视图:

= render partial: "photos", collection: @photos

是否有任何正确的方法来实施 w3school 的解决方案并在 Rails 循环中使用 Ruby 制作动态内容?

正在编辑原问题。我建议:

Each_slice: https://apidock.com/ruby/Enumerable/each_slice

in_groups_of 完全符合您的要求。

拆分或迭代大小为 number 的数组,填充 任何剩余的插槽 fill_with 除非它是 false.

%w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group}
["1", "2", "3"]
["4", "5", "6"]
["7", "8", "9"]
["10", nil, nil]

%w(1 2 3 4 5).in_groups_of(2, '&nbsp;') {|group| p group}
["1", "2"]
["3", "4"]
["5", "&nbsp;"]

%w(1 2 3 4 5).in_groups_of(2, false) {|group| p group}
["1", "2"]
["3", "4"]
["5"]