0
0

More than 3 years have passed since last update.

rails エラーメッセージ・フラッシュメッセージ

Posted at

記事投稿画面

posts/new.html.erb
<%@posts.errors.full_messages each do |message|%>・・1

<%=message%>・・エラーメッセージを表示
<textarea><%=@post.content%></textarea>・・直前の投稿内容を表示

・・1配列@posts.errors.full_messagesから要素を一つずつ取り出して変数messageに代入

*注意点

newアクションで@postが定義されないとエラーになる

Userモデルの作成

カラム名:name データ型:stringであるUserモデルの作成

$rails g model User name:string email:string

投稿が空のときにエラーメッセージはどうなるのかターミナルで確認

$rails console //コンソール(入力・出力の機能を備えた装置の機能)の起動
>post=Post.new(content:")//contentが空であるPostインスタンスの作成
>post.errors.full_messages
=>[] //保存失敗前にはからの配列が入っている
>post.save 
=>false //作成したPostインスタンスをPostテーブルに保存=>失敗
>post.errors.full_messages
=>[contentを入力してください]//保存失敗後にはエラーメッセージの配列が入っている

フラッシュメッセージ

フラッシュメッセージ・・ページ上に一度だけ表示されるページ
アクションで変数flash[:notice]に文字列を代入すると、flash[:notice]をビューで使える。
<%if flash[:notice]%>フラッシュメッセージが存在するときのみ表示

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