response_with&Flash Notice

我的一个控制器中有以下内容:

def create photo.user = current_user if current_user flash[:notice] = "The photos was saved" if photo.save respond_with photo, :location => photo_path(photo) end 

此代码有一个例外。 如果我使用某种AJAX访问此操作,然后访问另一个页面,将显示闪存通知。 如何在响应时显示flash通知:html? 我想也许你可以传递一个:notice =>“my flash”来respond_with但没有运气。

你可以把条件放在:

 flash[:notice] = "The photos was saved" if photo.save && !request.xhr? 

此外,如果有一天您在决定使用生成通知时响应AJAX请求,您可以使用flash.discard来清除闪存。

使用方法如下:

 respond_to do |format| format.html { redirect_to photo_path(photo), :notice => 'The photos was saved') } format.xml { render :xml => photo, :status => :created} end