2012-08-13 30 views
3

控制器中有一個動作。它只能通過ajax以json格式調用Rails 3.2.3和json中的Flash消息

def update 
    @article = Article.find_by_id params[:id] 
    respond_to do |format| 
     if @article.update_attributes(params[:article]) 
     flash[:message] = "good"  
     else 
     flash[:error] = @article.errors.full_messages.join(", ") 
     end 
      format.json { render :json => flash} 
    end 

end 

<% unless flash[:error].blank? %> 
    <%= flash[:error] %> 
<% end %> 

<% unless flash[:message].blank? %> 
    <%= flash[:notice] %> 
<% end %> 
<!-- page content goes --> 

當然的一部分,一個頁面包含一個button_to:remote=>true調用該方法update

底線是更新後不顯示任何內容。 JSON對象肯定會返回,我可以在fireBug中看到它。

問題是,我正確使用閃光?我如何使用它在頁面上顯示消息?請不要忘記阿賈克斯。

回答

-1

我認爲 你必須綁定ajax:success回調,它將通過替換消息或將消息放置到dom來顯示flash消息。

4

爲什麼在respond_to塊中有if/else語句?

def update 
    @article = Article.find_by_id params[:id] 
    if @article.update_attributes(params[:article]) 
    flash[:notice] = "Good" 
    else 
    flash.now[:notice] = "Bad" 
    render "edit" 
    end 
    respond_to do |format| 
    format.html {redirect_to @article} 
    format.js 
    end 
end 

然後創建上述update.js.erb

$("#notice").text("<%= escape_javascript(flash[:notice]) %>") 
$("#notice").show() 

代碼可能不是100%正確。

對於閃光,我有這樣的:

<div id="notice"> 
    <% flash.each do |key, value| %> 
    <%= content_tag(:div, value, :class => "flash #{key}") %> 
    <% end %> 
</div> 
+0

我問,我怎麼顯示Flash消息JSON對象?你回答js。 – Alexandre 2012-08-16 05:46:42

+0

完全困惑。如果您通過Ajax提交請求,它會響應'format.js'而不是'format.json',這只是針對json請求。 – veritas1 2012-08-16 11:34:32

+0

正如我所說的,我需要處理一個json請求。 – Alexandre 2012-08-16 14:58:23