2010-07-19 94 views
1

我正在通過ajax調用控制器的create操作,因此當對象成功保存時,會觸發js響應。但是,如果由於驗證而導致對象無法保存,那麼我希望響應爲html。我希望通過不返回其他塊中的js響應來實現此目的(請參閱下面的代碼),但這會產生406不可接受的錯誤。respond_to更改響應類型

有關如何做到這一點的任何想法?

我也可能注意到,我爲什麼要這麼做的原因是因爲我不能確定如何在驗證失敗時建立一個適當的js響應...

在此先感謝! =]

控制器創建行動

respond_to do |format| 
    if @person.save 
    flash[:notice] = 'Successfully created.' 
    format.html { redirect_to(@person) } 
    format.js 
    else 
    flash[:error] = 'There are errors while trying to create a new Person' 
    format.html { render :action => "new" } 
    end 
end 

回答

1

如果您特別要求在URL中的JS格式,那麼你必須爲你提供響應JS。其中一種選擇是在請求中不指定格式,然後僅對xhr進行過濾。像這樣:

respond_to do |format| 
    if @person.save 
    flash[:notice] = 'Successfully created.' 
    if request.xhr? 
     format.js 
    end 
    format.html { redirect_to(@person) } 
    else 
    flash[:error] = 'There are errors while trying to create a new Person' 
    format.html { render :action => "new" } 
    end 
end 

這樣一來,如果您不指定任何格式的請求時,它會先打JS,如果是一個XHR請求(即,一個AJAX請求),而如果有錯誤,它會返回HTML,無論如何。

這有道理嗎?

+0

啊,這正是我對這種情況所追求的!謝謝=] – 2010-07-19 22:05:01