LoginSignup
11
9

More than 5 years have passed since last update.

Railsで任意の要素数のデータをテーブルレイアウトで良い感じに表示したい

Last updated at Posted at 2014-03-11

やりたいこと

レコードの一覧を(やむなく)テーブルレイアウトで表示したい

Kobito.png

悩むところ

レコードの数は可変なので、レコード数で素直にテーブルレイアウトを実現しようとすると列数が半端な場合がでてきてしまう。

Kobito 2.png

解決方法

ActiveSupportで追加されるArray#in_groups_ofを使う。

in_groups_ofを使うと、配列を指定の列数で区切った2次元の表にしてくれ、且つ最終行で列数に満たない部分にはnilを入れてくれます。

%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, ' ') {|group| p group}
["1", "2"]
["3", "4"]
["5", " "]

これをレコードのコレクションに対して適用してあげれば、

<table>
  <% Post.all.in_groups_of(3) do |row| %>
    <tr>
      <% row.each do |post| %>
        <td>
          <% if post %>
            <%=link_to post.title, post %>
          <% end %>
        </td>
      <% end %>
    </tr>
  <% end %>
</table>

以下のような感じで奇麗なテーブルレイアウトを実現できるのであった。

Kobito 3.png

参考:

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9