2011-03-03 42 views
2

我試圖顯示一個Flash消息並使用Ajax呈現它,但消息似乎並沒有出現,直到我刷新頁面。在軌道上的紅寶石的阿賈克斯Flash消息

這是我的create.rjs文件:

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 

這裏是我的應用程序佈局視圖的相關部分:

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

這是我的微柱控制器的相關部分:

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 

那麼,爲什麼不立即顯示的Flash消息?

+0

看看這個答案很好的解決了這一點:http://stackoverflow.com/questions/366311/how-do-you-handle-rails-flash- with-ajax-requests – Peyman 2011-10-30 03:44:36

+0

不知道它是否會按照你想要的來做,但嘗試使用flash.now [:success] – 2012-08-07 15:51:56

回答

8

設計中的Flash消息存儲在會話中,直到下一頁加載。在ajax的情況下,請勿使用閃光燈。首先,用於替換消息的div可能不存在,因此您需要將該消息添加到您的頁面作爲要添加到的容器。其次,只需從常規變量中進行,而不是閃光。

定期變量將是:

@message = "Micropost created!" 

代替閃光燈[:成功]

JS的視圖將使用代替閃光燈此變量。

+0

我想我已經添加了div,但是對於這個樣子會使用一個常規變量呢? – 2011-03-03 23:58:48

1

而不是page.replace_html :notice, flash[:notice]
試試這個page.replace_html :notice, "Some info to flash"