Rails中使用flash总结

来源:互联网 发布:淘宝商家免费活动 编辑:程序博客网 时间:2024/05/20 01:37

Rails中使用flash总结

九 30th, 2011
发表评论 | Trackback

这个flash与Adobe/Macromedia Flash没有任何关系。
用于在两个actions间传递临时数据,flash中存放的所有数据会在紧接着的下一个action调用后清除。
一般用于传递提示和错误消息。

使用示例:
controller代码

class PostsController < ActionController::Base   
def create     # 保存post    
 flash[:notice] = "创建POST成功" # 可以直接写成notice = "创建POST成功"     
redirect_to posts_path(@post) # 上面两行可以写成 redirect_to posts_path(@post), :notice => "创建POST成功"  end  def show    # 不需要手动设置flash notice到template, 会自动设置。  endend

view代码: show.html.erb

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

一共有两种通知:notice与alert,分别表示“提示”和“错误警告”。
flash[:notice]与flash[:alert]有多种写法:
flash.notice=与flash.alert=
flash["notice"]与flash["alert"]
redirect_to时作为参数:alert => “…”, :notice => “…”

另外一个还会遇到的是flash.now[],它只对当前action有效,下一个action即无效
flash.now[:message] = “Hello current action”
flash.now[]设置的数据访问方法与其它相同:均为flash['my-key']

原理:
flash.new[]是保存在request中的。alert与notice是保存在session中的, 只是获取数据时添加了删除的逻辑。

注意:
flash[:alert],flash[:notice]一般与redirect_to一起用,而不能与render一起用。
redirect_to是重定向,会重新发起请求,比render多了一次请求。flash[:alert],flash[:notice]只会出现在接下面的一个页面中。
而render是服务器端转发,客户端不会重新发送请求,比redirect_to少了一次请求。所以一旦一起用,结果是接下来两个页面都有flash[:alert],flash[:notice],第三个页面时才会消失。
正确的做法是render搭配flash.now[:alert],flash.now[:notice]一起用

显示所有notice与alert的helper

application_helper.rb中添加:

  def display_notice_and_alert    msg = ''    msg << (content_tag :div, notice, :class => "notice") if notice    msg << (content_tag :div, alert, :class => "alert") if alert    sanitize msg  end

view中只需添加:

<%= display_notice_and_alert %>
0 0
原创粉丝点击