Action Dispatch Flash
Flash 提供了一种在操作之间传递临时基本类型(String
、Array
、Hash
)的方法。您放置在 flash 中的任何内容都将暴露给下一个操作,然后被清除。这是一种执行通知和警报的好方法,例如创建一个操作,在重定向到显示操作之前设置 flash[:notice] = "Post successfully created"
,然后显示操作可以将其暴露给其模板。实际上,这种暴露是自动完成的。
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 助手。
请记住:在执行下一个操作时,它们将消失。
有关 flash 的更多详细信息,请参阅 FlashHash
类的文档。
命名空间
方法
- 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