跳至内容 跳至搜索

Action Dispatch Flash

Flash 提供了一种在 action 之间传递临时原始类型(StringArrayHash)的方法。您放入 flash 的任何内容都将在下一个 action 中公开,然后被清除。这是实现通知和警报的绝佳方式,例如,一个 create action 在重定向到显示 action 之前设置 flash[:notice] = "Post successfully created",该显示 action 随后可以将其 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。当然,您也可以一次放入任意数量的字符串。如果您想传递非原始类型,则需要在应用程序中自行处理。例如:要显示带有链接的消息,您将需要使用 sanitize 辅助方法。

请记住:它们将在下一个 action 执行之前消失。

有关 flash 的更多详细信息,请参阅 FlashHash 类的文档。

命名空间
方法
N

常量

= "action_dispatch.request.flash_hash"
 

类公共方法

new(app)

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