LoginSignup
115
114

More than 5 years have passed since last update.

僕の中でRailsのflashの使い方が落ち着いてきた

Posted at

ご報告です。今まで試行錯誤という感じで使っていたのですが、Railsのflashの使い方が落ち着いてきました。

そもそもflashとは

セッションに一時的にメッセージを入れておける機能です。何も考えずに使うと次回のリクエストに有効です。

some_controller.rb
flash[:notice] = 'そのページはログインしないと見れないよ!'
redirect_to login_path

のように使うのが有効と思います。詳しくは調べてください。

Bootstrapとともに使う

上記のように説明されることが多い flash ですが、実態は Hash なので、任意のキーが使用できます。ぼくはよく Bootstrap を使うので、 Alerts コンポーネントと組み合わせて使っています。

some_controller.rb
flash[:success] = 'success!'
flash[:info] = 'info'
flash[:warning] = 'warning'
flash[:danger] = 'danger'
some_view.html.haml
- flash.each do |type, msg|
  %div{class: "alert alert-#{type}"}= msg

のようにするのに落ち着きました。

ご意見大歓迎です。

115
114
1

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
115
114