らくだ🐫にもできるRailsチュートリアル|10.3

10.3 すべてのユーザーを表示する

indexアクションを追加してユーザー一覧を表示させる →データベースにサンプルデータを追加する方法 →ページネーション(pagination=ページ分割)の方法 見本はこちら → RoRT本文

10.3.1 ユーザーの一覧ページ

ユーザーindexページはログインユーザーしか表示できないようにする

indexアクションのリダイレクト

UsersControllerTestにindexアクションが正しくリダイレクトするかを検証するテストを定義していく

require '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
    # users_pathにgetのリクエスト
    get users_path
    # login_urlにリダイレクトされる
    assert_redirected_to login_url
  end
・
・
・

indexアクションを定義 UsersControllerのbeforeフィルターのlogged_in_userにindexアクションを追加して保護

class UsersController < ApplicationController
  # 直前にlogged_in_userメソッドを実行 index,edit,updateアクションにのみ適用
  before_action :logged_in_user, only: [:index, :edit, :update]
  # 直前にcorrect_userメソッドを実行 edit,updateアクションにのみ適用
  before_action :correct_user,   only: [:edit, :update]
  
  def index
    #インスタンス変数@usersにすべてのuserを代入(後で修正あり)
    @users = User.all
  end
  
  def show
    @user = User.find(params[:id])
  end
・
・
・

indexページを作成

index.html.erbを作る

<% provide(:title, t('.all_users')) %>

<%= t('.all_users') %>

    <% @users.each do |user| %>
  • <%= gravatar_for user, size: 50 %> <%= link_to user.name, user %>
  • <% end %>

スタイルを整える

・
・
・
/* Users index */

.users {
  list-style: none;
  margin: 0;
  li {
    overflow: auto;
    padding: 10px 0;
    border-bottom: 1px solid $gray-lighter;
  }
}

ヘッダーにユーザー一覧表示用のリンクを追加