LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】ユーザー登録フォームの作成その3 ユーザー登録の成功【Rails Tutorial 7章まとめ】

Last updated at Posted at 2019-11-27

ユーザー登録成功時の処理

ユーザー登録に成功すると、なぜかnewページに戻る。
これはcreateアクションでユーザーが作成されたあと、対応するcreateビューに行こうとするが、createビューが存在しないためである。
createビューは必要ないため、ここではユーザーのプロフィールページにリダイレクトすることにする。

app/controllers/users_controller.rb
  def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "Welcome to the Sample App!"
      redirect_to user_url(@user)
    else
      render 'new'
    end
  end

user_url(@user)の行き先は/user/:idへのGETリクエストであり、showアクションに到達する。
また、リダイレクトの場合名前付きルートは_pathではなく_urlを使用する。
なお、user_url(@user)を単に@userと書いてもよいらしい。

flash変数を使って、ユーザー登録成功時のメッセージを表示している。

ユーザー登録成功時のテスト

ユーザー登録成功時のテストを書く。

test/integration/users_signup_test.rb
require 'test_helper'

class UsersSignupTest < ActionDispatch::IntegrationTest
  .
  .
  .
  test "valid signup information" do
    get signup_path
    assert_difference 'User.count', 1 do
      post users_path, params: { user: { name:  "Example User",
                                         email: "user@example.com",
                                         password:              "password",
                                         password_confirmation: "password" } }
    end
    follow_redirect!
    assert_template 'users/show'
    assert_not flash.empty?
  end
end

ユーザー登録失敗時のテストと基本は同じ。
こちらはassert_differenceを使っている。
これはブロックの前後で第一引数が第二引数分だけ増減したことを確認する。
ユーザー登録の成功により、User.countは1増えているはずである。

リダイレクト先に移動するにはfollow_redirect!を使う。

flashが表示されていることも確認しておく。

flashの表示

flashをレイアウトに追加して表示できるようにする。

app/views/layouts/application.html
  <body>
    <%= render 'layouts/header' %>
    <div class="container">
      <% flash.each do |message_type, message| %>
        <div class="alert alert-<%= message_type %>"><%= message %></div>
      <% end %>
      <%= yield %>
      <%= render 'layouts/footer' %>
      <%= debug(params) if Rails.env.development? %>
    </div>
    .
    .
    .
  </body>
0
0
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
0
0