はじめに

Railsで簡易メッセージをViewで表示するために用意されているflashオブジェクトについてメモしておきます。
Controllerからredirect_toメソッドでViewに渡すことが一般的です。

flashオブジェクトとは

ControllerからViewに簡易メッセージ(ログインメッセージ、エラーメッセージ)を送信し表示する場合に使います。

http://railsdoc.com/references/flash

使い方

Controller側(redirect_toメソッド)

redirect_toメソッドはオプションにnotice,alert,flashを用意しています。

notice例:

redirect_to action: 'index', notice: 'ログインに成功しました'

alert例:

redirect_to action: 'index', alert: 'ログインできません'

flash例:

redirect_to action: 'index', flash: {notice: 'ログインに成功しました'}

※flashでキーはオプションのnotice,alertのほか任意の名前でも可能です

http://railsdoc.com/references/redirect_to

View側

notice,alertを表示する例:※bootstrapでメッセージ枠を表示

<% if flash[:notice] %>
  <div class="alert alert-success">
    <%= flash[:notice] %>
  </div>
<% end %>
<% if flash[:alert] %>
  <div class="alert alert-danger">
    <%= flash[:alert] %>
  </div>
<% end %>

ifでnotice,alertの中身がある場合に表示とするのがよく使われる

その他おすすめの備忘録

 

One Response to [Rails]ControllerからViewへ簡易メッセージ表示するflashオブジェクトについて

  1. kdmgs110 より:

    flashをviewに引き渡すときのbootstrap

コメントを残す