LoginSignup
2
1

Rails の `render`の注意【Turbo】

Posted at

はじめに

「何をすればいいのか」はわかるけど、「なぜなのか」まではわかりませんでした・・・悔しい。

問題

ログイン処理のコードです。

class UserSessionsController < ApplicationController
  def new; end

  def create
    @user = login(params[:email], params[:password])
    if @user
      redirect_back_or_to(root_path, notice: I18n.t('flash.user_sessions.new'))
    else
      flash.now[:alert] = I18n.t('flash.user_sessions.new_failed')
      render :new, status: :unprocessable_entity
    end
  end

  def destroy
    logout
    redirect_to(root_path, notice: I18n.t('flash.user_sessions.logged_out'))
  end
end

問題は以下の部分

flash.now[:alert] = I18n.t('flash.user_sessions.new_failed')
render :new, status: :unprocessable_entity

status: :unprocessable_entityというのは、HTTPステータスコード422のことなのですが、
これを消すと

flash.now[:alert] = I18n.t('flash.user_sessions.new_failed')
render :new

flashの表示・ページのレンダーがされない、という問題が起きました。

renderはデフォルトで200 OKを返します。
つまり、「200 OK だとページがレンダされない」「422だとされる」ということです。なぜ?

解決方法

Turboの仕業でした。

Turboでは、renderで適切なステータスコードを選択しなかった場合、ページの再描画が行われない

だそうです。

renderなら422を指定しろ、それかredirectを使え

終わりに

めちゃくちゃ手こずりました。GPTも「ステータスコードは関係ないです」の一点張りだったし。
結局なんでかわからなかった。
なんでなんだろう・・・悔しい・・・

2
1
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
2
1