跳到內容 跳到搜尋

Action Dispatch Flash

Flash 提供在動作間傳遞臨時基本類型 (StringArrayHash) 的方式。您放置在 Flash 中的任何資料都會在下一項動作中公開,然後清空。這是執行通知和警示的絕佳方式,例如在重新導向到顯示動作之前設定 flash[:notice] = "Post successfully created" 的建立動作,讓此顯示動作可以將 Flash 顯示在範本中。實際上,會自動執行此顯示方式。

class PostsController < ActionController::Base
  def create
    # save post
    flash[:notice] = "Post successfully created"
    redirect_to @post
  end

  def show
    # doesn't need to assign the flash notice to the template, that's done automatically
  end
end

然後在 show.html.erb

<% if flash[:notice] %>
  <div class="notice"><%= flash[:notice] %></div>
<% end %>

由於 noticealert 鍵是常見表達語法,所以系統會提供便捷存取器

flash.alert = "You must be logged in"
flash.notice = "Post successfully created"

這個範例會在 Flash 中放置一個字串。當然,您也可以一次放置多個字串。如果您想要傳遞非基本類型,請在應用程式中處理。範例:若要顯示具有連結的訊息,您必須使用 sanitise 輔助程式。

請牢記:它們將會在執行下一動作時消失。

參閱 FlashHash 類別的說明文件,以取得有關 Flash 的更多詳細資料。

名稱空間
方法
N

常數

KEY = "action_dispatch.request.flash_hash"
 

類別公開方法

new(app)

# File actionpack/lib/action_dispatch/middleware/flash.rb, line 312
def self.new(app) app; end