Ruby on Railsで作るユーザー投稿型Webアプリケーション②

前回に引き続き、ユーザー投稿型 Web アプリケーション作成していきます。

今回はユーザー関連機能を作っていきます。

index 作成

このままだと画面遷移が不便なので、index 画面を作成していきます。

以下のコマンドを入力してください。

rails g controller top index

次にルーティングを作成しましょう。

/project/config/routes.rb

Rails.application.routes.draw do get ’top/index’ devise_for :users root :to => ’top#index'

For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

end

試しに起動してみましょう。

rails s

ドキュメントルートにアクセスすると以下にが表示されるはずです。
確認してください。

次にログインリンクを作成します。

ログインと新規登録は全ての画面からアクセスできるようにするのが望ましいので、application.erb.html に追記します。

/project/app/views/layouts/application.html.erb

Project <%= csrf\_meta\_tags %> <%= csp\_meta\_tag %>
<%= stylesheet\_link\_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript\_include\_tag 'application', 'data-turbolinks-track': 'reload' %>
<% if user\_signed\_in? %>
  • <%= link\_to "home", root\_path %>
  • <%= link\_to "logout", destroy\_user\_session\_path, method: :delete %>
  • <% else %>
  • <%= link\_to "HOME", root\_path %>
  • <%= link\_to "sign up", new\_user\_registration\_path %>
  • <%= link\_to "login", new\_user\_session\_path %>
  • <% end %> <%= yield %>

    Users コントローラー作成

    次に Users コントローラーを作成しそれぞれ機能を追加していきます。

    rails g controller users index edit show

    ルーティングは以下の通り登録します。

    Rails.application.routes.draw do devise_for :users root :to => ’top#index’ resources :users, only: [:index, :edit, :show, :update]

    For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

    end

    /project/app/controllers/users_controller.rb

    class UsersController < ApplicationController def index @userId = current_user.id @users = User.all end end

    次にユーザールートの index.html.erb を編集します。

    /project/app/views/users/index.html.erb

    /project/app/views/users/index.html.erb

    Users#index

    Find me in app/views/users/index.html.erb

    <%= link\_to "プロフィール編集", edit\_user\_path(@userId) %>

      <% @users.each do |user| %>
    • <%= user.name %>
    • <% end %>

    画面遷移するために必要な機能を追加したので、次にヘッダーリンクに users を追記します。

    /project/app/views/layouts/application.html.erb

    Project <%= csrf\_meta\_tags %> <%= csp\_meta\_tag %>
    <%= stylesheet\_link\_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript\_include\_tag 'application', 'data-turbolinks-track': 'reload' %>
    
    <% if user\_signed\_in? %>
  • <%= link\_to "home", root\_path %>
  • <%= link\_to "users", users\_path %>
  • <%= link\_to "logout", destroy\_user\_session\_path, method: :delete %>
  • <% else %>
  • <%= link\_to "HOME", root\_path %>
  • <%= link\_to "sign up", new\_user\_registration\_path %>
  • <%= link\_to "login", new\_user\_session\_path %>
  • <% end %> <%= yield %>

    ユーザー編集画面作成

    ユーザーの編集機能を追加します。

    その前にユーザー画像設定用にファイルアップロード機能を追加します。

    GemFile の最終行に以下を追記してください。

    /project/Gemfile

    gem “refile”, require: “refile/rails”, github: ‘manfe/refile’ gem “refile-mini_magick”

    bundle install

    ユーザー画像投稿用のカラムを作成します。

    rails g migration AddProfileImageIdToUsers profile_image_id:string

    次にユーザー情報と画像レコードを紐づけるためのカラムを追加します。

    /project/db/migrate/[作成日時]_devise_create_users.rb

    # frozen_string_literal: true

    class DeviseCreateUsers < ActiveRecord::Migration[5.2] def change create_table :users do |t| ## Database authenticatable t.string :name, null: false, default: "" t.string :email, null: false, default: "" t.string :encrypted_password, null: false, default: "" t.string :introduction, null: false, default: "" t.string :profile_image, null: false, default: "" # 追加

      ## Recoverable
      t.string   :reset\_password\_token
      t.datetime :reset\_password\_sent\_at
    
      ## Rememberable
      t.datetime :remember\_created\_at
    
      ## Trackable
      # t.integer  :sign\_in\_count, default: 0, null: false
      # t.datetime :current\_sign\_in\_at
      # t.datetime :last\_sign\_in\_at
      # t.string   :current\_sign\_in\_ip
      # t.string   :last\_sign\_in\_ip
    
      ## Confirmable
      # t.string   :confirmation\_token
      # t.datetime :confirmed\_at
      # t.datetime :confirmation\_sent\_at
      # t.string   :unconfirmed\_email # Only if using reconfirmable
    
      ## Lockable
      # t.integer  :failed\_attempts, default: 0, null: false # Only if lock strategy is :failed\_attempts
      # t.string   :unlock\_token # Only if unlock strategy is :email or :both
      # t.datetime :locked\_at
    
      t.timestamps null: false
    end
    
    add\_index :users, :email,                unique: true
    add\_index :users, :reset\_password\_token, unique: true
    # add\_index :users, :confirmation\_token,   unique: true
    # add\_index :users, :unlock\_token,         unique: true
    

    end end

    User モデルに UserImage を紐づける

    /project/app/models/user.rb

    class User < ApplicationRecord

    Include default devise modules. Others available are:

    :confirmable, :lockable, :timeoutable, :trackable and :omniauthable

    devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable attachment :profile_image end

    /project/app/views/users/edit.html.erb

    Users#edit

    Find me in app/views/users/edit.html.erb

    プロフィール編集

    <%= form\_with model:@user, local:true do |f| %> <%= f.text\_field :name, autofocus: true, id:"inputName", placeholder:"名前"%> <%= f.text\_field :introduction, autofocus: true, id:"inputIntroduction", placeholder:"自己紹介"%> <%= attachment\_image\_tag @user, :profile\_image, :fill, 60, 60, fallback: "【ユーザー画像が設定されてない場合に表示する画像URLを設定】"%>

    <%= f.attachment_field :profile_image, placeholder: “プロフィール画像” %> <%= f.submit “変更を保存” %> <% end %>

    /project/app/controllers/users_controller.rb

    class UsersController < ApplicationController def index @userId = current_user.id @users = User.all end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) @user.update(user_params) redirect_to user_path(@user.id)
    end

    private

    def user_params params.require(:user).permit(:introduction, :name, :profile_image) end end

    リンクから編集画面に遷移してください。以下画面が表示されたら成功です。

    ユーザー一覧画面作成

    次にユーザーの詳細画面を作成します。

    ルーティング変更するので以下のように修正してください。

    /project/config/routes.rb

    Rails.application.routes.draw do devise_for :users root :to => ’top#index’ resources :users do resources :id end

    For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

    end

    次に user のルートパスで表示されている全ユーザーの詳細画面へのパスを記載します。

    /project/app/views/users/index.html.erb

    Users#index

    Find me in app/views/users/index.html.erb

    <%= link\_to "プロフィール編集", edit\_user\_path(@userId) %>

      <% @users.each do |user| %>
    • image

      <%= attachment\_image\_tag user, :profile\_image, :fill, 60, 60, fallback: "no\_image.jpg"%>

      name

      <%= user.name %>

      詳細画面へ

      <%= link\_to "show", user\_path(user) %>
    • <% end %>

    /project/app/controllers/users_controller.rb

    class UsersController < ApplicationController def index @userId = current_user.id @users = User.all end def show @user = User.find(params[:id]) end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) @user.update(user_params) redirect_to user_path(@user.id)
    end

    private

    def user_params params.require(:user).permit(:introduction, :name, :profile_image) end end

    /users に遷移して確認してください。登録ユーザーのプロファイル画像と名前、それぞれの詳細画面への遷移ボタンが表示されるかと思います。

    今回は以上となります。