LoginSignup
0
0

More than 1 year has passed since last update.

Railsでエラーメッセージ表示されない時の対処法

Posted at

mac OS バージョン11.6
Rails 6.0.4

やりたいこと

ユーザー登録に失敗した場合、エラーメッセージが出るようにする

エラー内容

どこか1つを空欄で登録しようとした場合、本来ならエラーメッセージが出るはずだが出ない。

66c676ebe92b0cec674b3199da319983.png

原因

form_withがajax通信になっていたので、画面が更新されていなかった。

Rails 5.1〜6.0 の form_with ではデフォルトでajax通信が行われる仕様になっていて、非同期通信になってしまうのです。
ここにlocal: trueと引数を渡す事で、HTMLをレンダリングできるようになります。(Railsの6.1からはデフォルトでajaxではなくなったのでlocal: trueは不要です)

解決策

local: trueを設定することでajax通信を無効にする。

users/new.html.erb
<%= form_with(model: @user) do |f| %>
      <%= render 'layouts/error_messages', model: f.object %>

<%= form_with(model: @user, local: true) do |f| %>
      <%= render 'layouts/error_messages', model: f.object %>

参考

https://ecoyamas.biz/102
https://qiita.com/kakudaisuke/items/e032c7705db00e8081dc?utm_campaign=popular_items&utm_medium=feed&utm_source=popular_items

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