はじめに
twitterのようなアプリで投稿する際のサクセスメッセージやエラーメッセージの出し方についてまとめてみました。僕自身初めてこの機能をつける時手間だったので同じような悩みを持つ人のために投稿します。
バージョン
ruby 2.5.7
Rails 5.2.4.3
サクセスメッセージの出し方
コントローラー
flash[:notice] = "successfully"
コントローラーのcreateアクションとupdateアクションのなかに↑の記述をします。
ビュー
<% if flash[:notice] %>
<p id="notice">
<%= flash[:notice] %>
</p>
<% end %>
サクセスメッセージを出したいビューのページに↑の記述をします。
これで、投稿できた際に"successfully"という文字が出てくると思います。
エラーメッセージの出し方
コントローラー
def create
@book = Book.new(book_params)
@book.user_id = current_user.id
if @book.save
flash[:notice] = "successfully"
redirect_to book_path(@book)
#ここから
else
@books = Book.all
render 'index'
#ここまで
end
end
よくエラー起きるのがここです。saveができなかったときの動作を記述しましょう
ビュー
<% if @book.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:</h2>
<ul>
<% @book.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
エラーメッセージを出したいビューとコントローラーに↑を記述します。
そうすれば、バリデーションに引っかかって投稿できない時にエラーメッセージが出てくるでしょう。
最後に
詳しく知りたい方はこちらも参考にしてみてください。