Ruby on Rails中的Ajax闪光灯消息 [英] Ajax flash message in ruby on rails

查看:174
本文介绍了Ruby on Rails中的Ajax闪光灯消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图表现出显信息,并使用Ajax呈现它,但似乎该消息并没有现身后我才刷新页面。

I'm trying to show a flash message and render it with Ajax, but the message does not seem to be appearing until after I refresh the page.

下面是我的create.rjs文件:

Here's my create.rjs file:

page.insert_html :top, :feed_items, :partial => 'shared/feed_item', :object => @micropost
page.replace_html :user_info, pluralize(current_user.microposts.count, "micropost")
page[:micropost_form].reset
page.replace_html :notice, flash[:notice]
flash.discard

下面是我的应用程序布局视图中的相关部分:

Here's the relevant part of my application layout view:

<div id= "notice"><% flash.each do |key, value| %>
   <div class="flash <%= key %>"><%= value %></div>
<% end %></div>

这是我的micropost控制器的相关部分:

And here's the relevant part of my micropost controller:

class MicropostsController < ApplicationController
  before_filter :authenticate, :only => [:create, :destroy]
  before_filter :authorized_user, :only => :destroy

  def create
    @micropost  = current_user.microposts.build(params[:micropost])
    respond_to do |format|
      if @micropost.save
        flash[:success] = "Micropost created!"

        format.html { redirect_to root_path }
        format.js   
      else
        @feed_items = []
        render 'pages/home'
      end  
    end
  end

那么,为什么不闪动信息显示出来,对吗?

So why isn't the flash message showing up right away?

推荐答案

在设计的Flash消息存储在会话中,直到下一个页面加载。在AJAX的情况下,不要使用闪光灯。一方面,股利更换消息到可能不存在,所以你需要添加到您的网页作为容器添加到。其次,只是从一个普通的变量,不闪。

Flash messages by design are stored in the session until the next page load. In the case of ajax, don't use flash. For one thing, the div to replace the message into may not exist, so you need to add that to your page as a container to add to. Second, just do it from a regular variable, not flash.

一个常规的变量是:

@message = "Micropost created!"

而不闪

[:成功]

instead of the flash[:success]

JS的看法会用闪存代替这个变量。

The js view would use this variable instead of flash.

这篇关于Ruby on Rails中的Ajax闪光灯消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆