2011-06-01 46 views
7

我已經在我的控制器之一以下:respond_with&閃光通知

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進行響應時只顯示flash通知?我想也許你可以通過:通知=>「我的閃光燈」respond_with,但沒有運氣。

回答

9

你可以把條件,如:

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

而且,如果有那麼一天,你會響應AJAX請求時,決定使用產生的通知, 可以使用flash.discard清除閃光。

-1

用途如下:

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

這就是我以前的想法,但我試圖從'respond_to'移到更緊縮的'respond_with'。 – 2011-06-01 18:07:31

+0

不得不downvote,因爲答案沒有試圖回答關於使用'respond_with'的海報問題。 – 2013-02-14 20:05:36

+0

@LesterPeabody,但它提供了一個解決方案。答案之後可能已經編輯過這個問題(儘管我不確定2年前發生了什麼)。我沒有downvote的問題,但可能更多的思想應該在運用之前應用。 – 2013-07-10 09:13:34