エラーメッセージの表示方法
バリデーションに失敗した場合、エラーメッセージが自動的に作られ、@note.errors.full_messages
でその内容を配列として取得できる。
モデルには以下のようにサンプルで記述する。
class Note < ActiveRecord::Base validates :title, presence: true validates :content, presence: true, length: { maximum: 140} end
viewには以下のように記述する。
new.html.erb #@note.errors.full_messagesにエラーメッセージの配列が入っているので、下記のコード全て表示することができる。 <% @note.errors.full_messages.each do |message| %> #full_messageの部分がエラーメッセージの配列になっている。 <%= message %> <% end %>
◯◯件のエラーがありますと表示するには下記のように記述する。
new.html.erb <%= if @note.errors.any? %> #any?でオブジェクトがひとつでもあればtrueを返す <h2><%= @note.errors.count %>件のエラーがあります。</h2>