在Ruby中使用flash传递消息
这个flash与Adobe/Macromedia Flash没有任何关系。
用于在两个actions间传递临时数据,flash中存放的所有数据会在紧接着的下一个action调用后清除。
一般用于传递提示和错误消息。
?
一共有两种通知: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]一起用
application_helper.rb中添加:
<%= display_notice_and_alert %>
?
?
原文:http://rubyer.me/blog/407
?