Rails中使用flash总结

来自老宋:http://rubyer.me/blog/407/

 

这个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, 会自动设置。
  end
end

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值