flashの書き方

flashの書き方

自分は最初にこの書き方を覚えました

flash[:キー名] = "テキスト"

デバックしてみると以下のようにハッシュの形式になっています。

pry

> flash
=> #<ActionDispatch::Flash::FlashHash:0x00007f9957294508 @discard=#<Set: {}>, @flashes={"danger"=>"ログインに失敗しました"}, @now=nil>

また、このようにも書けます。

flash: {キー名: "テキスト"}

view側で呼び出すには以下のように書きます。

<%= flash[:キー名] %>

flashで使用するkeyについて

Railsのデフォルトではnoticealertのみ使用できます。

デフォルトではこの2つは以下のようにflashを省略できます。

#before
redirect_to root_path, flash: {notice: "falshです"}

#after
redirect_to root_path, notice: "flashです"

view では以下のように呼び出せます。

<%= notice %>

他のkyeも上記のように省略して書きたい場合はadd_flash_typesメソッドを使用します。

ここではBootstrapを使用した場合を考えてみます。 Bootstrapではいくつかのkeyにstyleが設定されています。以下の表はその中の一例です。

Key Style
success Image from Gyazo
danger Image from Gyazo
info Image from Gyazo
warning Image from Gyazo

これらをadd_flash_typesメソッドを使用してRailsのデフォルトに追加するには以下のコードを加えます。

controllers/application_controller.rb

class ApplicationController < ActionController::Base
  add_flash_types :success, :danger, :info, :warning
end

これを追加する事で4つkeyもflashを省略して書くことができす。

redirect_to root_path, success: "flashです"

その他

flash.nowflash.keepflash部分のパーシャルについては以下の記事が分かりやすいです。

https://pikawaka.com/rails/flash#flash%E3%83%A1%E3%83%83%E3%82%BB%E3%83%BC%E3%82%B8%E3%81%ABbootstarp%E3%81%AE%E3%83%87%E3%82%B6%E3%82%A4%E3%83%B3%E3%82%92%E5%BD%93%E3%81%A6%E3%81%A6%E3%81%BF%E3%82%88%E3%81%86