flashとは
paramsと似たような存在。
ハッシュなので、キーを指定しなければならない。
paramsと違い、画面遷移を1回までは、データを保持したままにしてくれる。
制作物
以下のコードからは、bootstrapを前提としているが、レイアウトを気にしなければ参考になるはず。
<%= yield %>の上にflash用のdivを用意する。
flash[:info]における、[:info]はキーにあたる。
flash[:oshirase]と定義しても問題ない。
application/html/erb
<main>
<div class="my-2 bg-warning text-center text-dark" id="flash_error"><%=flash[:error]%></div>
<div class="my-2 bg-info text-center text-dark" id="flash_info"><%=flash[:info]%></div>
<div class="container">
<%= yield %>
</div>
</main>
本の投稿を例にあげる。
books_controller.rb
def create
@book=Book.new(book_params)
if @book.save
flash[:info]="成功しました。"
redirect_to .....
else
flash[:error]="保存に失敗しました。"
render "books/new" #もといたページ
end