Action Dispatch Flash
Flash 提供一種方式,可以在動作之間傳遞暫時的基本型別 (String
、Array
、Hash
)。您放置在 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 %>
由於 notice
和 alert
鍵是常見慣用語,因此可以使用方便的存取器
flash.alert = "You must be logged in"
flash.notice = "Post successfully created"
此範例在 Flash 中放置一個字串。當然,您一次也可以放置任意多個字串。如果您要傳遞非基本型別,您必須在應用程式中處理。範例:若要顯示包含連結的訊息,您必須使用 sanitize 輔助函數。
請記住:它們會在執行下一個動作時消失。
請參閱 FlashHash
類別的說明文件,以取得有關 Flash 的更多詳細資訊。
命名空間
方法
- N
常數
KEY | = | "action_dispatch.request.flash_hash" |
類別公開方法
new(app) 連結
來源:顯示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/middleware/flash.rb, line 300 def self.new(app) app; end