Rails 入力フォームのバリデーションエラーを表示するメモ
#app/views/posts/_form.html.erb
<%= form_with model: post, local: true do |form| %>
<%= render 'shared/error_messages', object: form.object %>
<%= form.label :content %>
<%= form.text_field :content %>
<%= form.submit %>
<% end %>
#app/views/shared/_error_messages.html.erb
<% if object.errors.any? %>
<% object.errors.full_messages.each do |msg| %>
<%= msg %>
<% end %>
<% end %>
パーシャル(app/views/shared/_error_messages.html.erb)にobjectがエラーを持っていれば繰り返しエラー文を表示するeach文を書く。
form_with内でパーシャルを呼び出す。この時、objectオプションでobjectにmodel(postモデル)を渡している。
これで入力フォームでバリデーションエラーが発生した時エラー文を表示してくれる。エラー文のモデル名の日本語変換はi18nのモデルの設定で行う。
ja:
activerecord:
models:
post: 投稿
attributes:
id: ID
content: コンテンツ
この記事が気に入ったらサポートをしてみませんか?