2013-10-08 25 views
0

我想在rails中使用ajax請求(設置remote :: true)重定向。這是我的問題。在ajax調用期間render或redirect_to在rails中的問題

在控制器中,我有:

def create 
    user = User.new 
    user.attributes = params[:user] 

    if user.save 
    if request.xhr? 
     flash[:notice] = "User successfully created" 
     render js: %('#{user_url(user.id)}') 
    end 
    else 
    if request.xhr? 
     render partial: "form" 
    else 
     render action: 'new' 
    end 
    end 
end 

模型,

class user 
    validates :total_amount, presence: true, numericality: {greater_than: 0} 
end 
視圖

,在JavaScript是:

$("#new_user").bind("ajax:success", function(evt, data){ 
if(data.length < 300){ 
    window.location.replace(data.replace(/['\s]/gi, '')); # on success rendering the url. 
    } 
    else { 
    $("#errors").html($(data)); # if there are any errors, i have a div tag around form, which will replace the form html 
    } 
}); 

當我點擊提交(其是一個ajax請求)爲用戶留下總量爲0.0(這是必需的),我得到驗證錯誤,這是預期的行爲(和顯示驗證錯誤,這是javascript中的其他部分)。 現在我輸入數量爲1.0並點擊提交(這也是一個Ajax請求)。它不會去javascript中的if部分。

我在這裏做錯了什麼?

回答

0

而不是檢查數據的長度,您應該使用ajax:errorajax:success作爲兩個不同的回調。錯誤回調顯示錯誤,成功重定向。

回調:https://github.com/rails/jquery-ujs/wiki/ajax

+0

其發射'AJAX:success'爲兩種情況。不知道爲什麼。 – Kumar

+0

什麼是完整的控制器操作代碼? – AJcodez

+0

更新了控制器代碼。 – Kumar