10.3 すべてのユーザーを表示する
indexアクションを追加しましょう。このアクションは、すべてのユーザーを一覧表示します。
その際、データベースにサンプルデータを追加する方法や、
将来ユーザー数が膨大になってもindexページを問題なく表示できるようにするためのユーザー出力のページネーション (pagination=ページ分割) の方法を学びます。
10.3.1 ユーザーの一覧ページ
ユーザーの一覧ページを実装するために、まずはセキュリティモデルについて考えてみましょう。
ユーザーのshowページについては、今後も(ログインしているか
どうかに関わらず) サイトを訪れたすべてのユーザーから見えるようにしておきますが
ユーザーのindexページはログインしたユーザーにしか見せないようにし、未登録のユーザーがデフォルトで表示できるページを制限します。
indexアクションのリダイレクトをテストする redtest/controllers/users_controller_test.rbrequire 'test_helper'
class UsersControllerTest < ActionDispatch::IntegrationTest
  def setup
    @user       = users(:michael)
    @other_user = users(:archer)
  end
  test "should redirect index when not logged in" do
    get users_path
    assert_redirected_to login_url
  end
  .
  .
  .
end
beforeフィルターのlogged_in_userにindexアクションを追加して、
このアクションを保護します
indexアクションにはログインを要求する greenapp/controllers/users_controller.rbclass UsersController < ApplicationController
  before_action :logged_in_user, only: [:index, :edit, :update]
  before_action :correct_user,   only: [:edit, :update]
  def index
  end
  def show
    @user = User.find(params[:id])
  end
  .
  .
  .
end
今度はすべてのユーザーを表示するために、全ユーザーが格納された変数を作成し、順々に表示するindexビューを実装します。
User.allを使ってデータベース上の全ユーザーを取得し、
ビューで使えるインスタンス変数@usersに代入させます。
ユーザーのindexアクション
app/controllers/users_controller.rb class UsersController < ApplicationController before_action :logged_in_user, only: [:index, :edit, :update] . . . def index @users = User.all end . . . end
実際のindexページを作成するには、ユーザーを列挙してユーザーごとにliタグで囲むビューを作成する必要があります。
ここではeachメソッドを使って作成します。
それぞれの行をリストタグulで囲いながら、
各ユーザーのGravatarと名前を表示します。

