ユーザー一覧画面の作成

ユーザー一覧画面の作成

今回はユーザーの一覧画面を作成していく。

作業の流れとしては下記の手順にて行う。

  1. コントローラの作成

  2. ルーティングの確認

  3. ビューの作成

  4. 動作確認

コントローラの作成

ユーザーの一覧画面はusersコントローラのindexアクションに記述していく。

app_controllers/users/controller.rb

  def index
    @users = User.all
    @user = current_user
    @book = Book.new
  end

解説)

@users = User.all

Userモデルの全データを取得する。

@user = current_user

インスタンス変数@userは現在ログインしているユーザーであると指定。

@book = Book.new

Bookクラスに空のインスタンスを作り、@bookへ代入する。

ルーティングの確認

ルーティングの記述を確認する。

config/routes.rb(usersの部分を抜粋)

resources :users, only: [:index, :show, :update, :edit]

上記のようにindexアクションが定義されていれば問題ない。記述が足りない場合、追加。

ビューの作成

users/indexにビューを記述していく。

app/views/users/index.html.erb

<div>
  <div>
    <div>
      <!--ユーザー情報-->
      <h2>User info</h2>
      <%= image_tag @user.get_profile_image(100,100) %>
      <table>
        <tbody>
          <tr></tr>
          <tr>
            <th>name</th>
            <th><%= @user.name %></th>
          </tr>
          <tr>
            <th>introduction</th>
            <th><%= @user.introduction %></th>
          </tr>
        </tbody>
      </table>

      <div>
        <%= link_to edit_user_path(@user) do %>
          <i class="fas fa-user-cog"></i>
        <% end %>
      </div>

      <!--本の投稿機能-->
      <h2>New book</h2>
      <%= form_with model: @book do |f| %>
        <div>
          <%= f.label :title %>
          <%= f.text_field :title %>
        </div>
        <div>
          <%= f.label :opinion %>
          <%= f.text_area :body %>
        </div>
        <div>
          <%= f.submit 'Create Book' %>
        </div>
      <% end %>
    </div>


    <!--ユーザーの一覧表示-->
    <div>
      <h2>Users</h2>
      <table>
        <thead>
          <tr>
            <th>image</th>
            <th>name</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <% @users.each do |user| %>
            <tr>
              <td><%= image_tag user.get_profile_image(80,80) %></td>
              <td><%= user.name %></td>
              <td>
                <%= link_to "Show", user_path(user.id) %>
              </td>
            </tr>
          <% end %>
        </tbody>
      </table>
    </div>
  </div>
</div>

動作確認

下記の内容の動作を確認する。

  • ヘッダーのUsersボタンを押した際にusers/indexに遷移する

  • users/index画面の表示が問題ない

  • users/indexのユーザー情報が問題なく表示される。ユーザー編集リンクから編集画面に遷移できる

  • bookの新規投稿が行える

以上。

アプリケーションの作成 参考URL  作成するアプリケーションについて - takifugu’s blog