2012-08-13 31 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