fc2ブログ

2023.08 «  - - - - - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 » 2023.10
TOP > rails の flash を使ってみる・その3【flash.keep と flash.discard】

 ← ☆★☆★☆★☆ 祝・ビバ100エントリ ☆★☆★☆★☆ | TOP | rails の flash を使ってみる・その2【flash.now】

rails の flash を使ってみる・その3【flash.keep と flash.discard】 

2007年12月21日 ()
flash は今の画面(アクション)と次の画面(アクション)まで有効だ、ということでしたが、次の次の画面(アクション)まで有効にする手段があります。

それは、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 を使うか、というのはあなた次第です!!ウマイ使い方、考えてみてください!

【広告】

[2007.12.21(Fri) 01:51] flashTrackback(0) | Comments(0)
↑TOPへ

 ← ☆★☆★☆★☆ 祝・ビバ100エントリ ☆★☆★☆★☆ | TOP | rails の flash を使ってみる・その2【flash.now】

COMMENT

COMMENT POST















管理者にだけ表示

 ← ☆★☆★☆★☆ 祝・ビバ100エントリ ☆★☆★☆★☆ | TOP | rails の flash を使ってみる・その2【flash.now】