rails の flash を使ってみる・その3【flash.keep と flash.discard】
それは、flash.keep
うーん、分かりやすいネーミングですね。
flash.keep とは対照的に、次の画面(アクション)まで有効だった flash を、今の画面(アクション)限りで消し去る、というメソッドもあります。
それは、flash.discard
例を見てみますか。
app/controllers/flash_example_controller.rb
class FlashExampleController < ApplicationController
layout 'my_layout'
def page1
flash[:msg1] = 'カンパネルラ'
flash.now[:msg2] = 'しのざき美知'
flash[:msg3] = '日焼けサロン'
flash.now[:msg4] = '金のエンゼル'
flash.discard(:msg1) # msg1 は、今回の画面は生きる。次の画面では消えてしまう。つまり、flash.now っぽくなる。
flash.discard(:msg2) # msg2 も、今回の画面は生きる。次の画面では消えてしまう。つまり、flash.now のままの動作をする。
end
def page2
flash.keep(:msg3) # msg3 は、今回の画面限りで消えるはずだったが、flash.keep されたので、次の画面も生きる。
end
def page3
end
end
app/views/layouts/my_layout.rhtml
<%= flash[:msg1] if flash[:msg1] %>
<%= flash[:msg2] if flash[:msg2] %>
<%= flash[:msg3] if flash[:msg3] %>
<%= flash[:msg4] if flash[:msg4] %>
<%= yield %>
app/views/flash_example/page1.rhtml
this is page 1
<%= link_to('page2へのリンク', :action => 'page2') %>
app/views/flash_example/page2.rhtml
this is page 2
<%= link_to('page3へのリンク', :action => 'page3') %>
app/views/flash_example/page3.rhtml
this is page 3
そして、各画面がどういう風に表示されるかというと、
http://localhost:3000/flash_example/page1
カンパネルラ しのざき美知 日焼けサロン 金のエンゼル this is page 1 page2へのリンク
flash の msg1~4 まで勢揃いです。
http://localhost:3000/flash_example/page2
日焼けサロン this is page 2 page3へのリンク
msg3 だけになりました。
http://localhost:3000/flash_example/page2
日焼けサロン this is page 3
msg3 はまだ健在です。
となります。しかしまあ、何に flash を使うか、というのはあなた次第です!!ウマイ使い方、考えてみてください!
【広告】