加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Rails中使用flash总结

发布时间:2020-12-15 20:12:22 所属栏目:百科 来源:网络整理
导读:Rails中使用flash总结 九 30th,2011 发表评论?|? Trackback 这个flash与Adobe/Macromedia Flash没有任何关系。 用于在两个actions间传递临时数据,flash中存放的所有数据会在紧接着的下一个action调用后清除。 一般用于传递提示和错误消息。 使用示例: cont

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,会自动设置。
  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 %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读