2014-10-27 40 views
0

我正在嘗試編寫一個Ajax調用,用於檢查用戶輸入到表單中的電子郵件地址是否已經存在於數據庫中。我檢查並仔細檢查了我的路線,但無法找出問題所在。有多個類似的SO問題,但其中大多數似乎是問題在於有人將路線定義爲getroutes.rb中,但是使用post進行了Ajax呼叫,反之亦然。那我得到的錯誤是:POST http://localhost:3000/registrations/validate_uniqueness 404 (Not Found)Ajax調用在Rails 3.2應用程序中404/500錯誤(路由選中)

routes.rb 

post '/registrations/validate_uniqueness' => 'registrations#validate_uniqueness' 

...

registrations_controller.rb 

    def validate_uniqueness 
    if User.find_by_email(params[:email]) 
     render :json => { value: true } 
    else 
     render :json => { value: false } 
    end 
    end 

...

Ajax call, when successful should assign a boolean value to the `exists` variable 

function validateUserFields() { 
    $.ajax({ 
    type: "POST", 
    url: "/registrations/validate_uniqueness", 
    dataType: "json", 
    data: {email: $("#user_email").val()}, 
    success: function() { 
     var exists = value; 
     alert(value); 
    }, 
    error: alert("Error!") 
    }) 
... 

更新 我改變了控制器動作看像這樣:

def validate_uniqueness 
    respond_to do |format| 
     format.json do 
     if User.find_by_email(params[:email]) 
      render :json => { value: true } 
     else 
      render :json => { value: false } 
     end 
     end 
    end 
    end 

仍然得到404錯誤

第二個編輯 想出瞭如何使用Chrome的開發工具,看看我的Ajax請求的詳細信息。這是完整的錯誤消息,從設計:

Unknown action 

Could not find devise mapping for path "/registrations/validate_uniqueness".This may happen for two reasons:1) You forgot to wrap your route inside the scope block. For example: devise_scope :user do get "/some/route" => "some_devise_controller" end2) You are testing a Devise controller bypassing the router. If so, you can explicitly tell Devise which mapping to use: @request.env["devise.mapping"] = Devise.mappings[:user] 

因此,我改變routes.rb到:

devise_scope :user do 
    post '/registrations/validate_uniqueness' => 'registrations#validate_uniqueness' 
    end 

這是朝着正確方向邁出的一步,但現在我越來越:

Uncaught ReferenceError: value is not defined

+0

您在validate_uniqueness方法中忘記了'end'子句。乾杯! – emaxi 2014-10-27 21:52:20

+0

是的,剛剛注意到並添加了第四個'end'。仍然收到錯誤! – sixty4bit 2014-10-27 21:54:17

+0

您可以打印本地Web服務器日誌記錄輸出嗎?你如何開始你的應用程序? – emaxi 2014-10-27 21:57:21

回答

0

如果您只想要成功/失敗響應,請在控制器中使用此功能:

def validate_uniqueness 
    if User.find_by_email(params[:email]) 
    head :no_content # returns 204 NO CONTENT and triggers success callback 
    else 
    head :not_found # returns 404 NOT FOUND and triggers error callback 
    end 
end 

然後刪除對JS中的響應值的任何引用,因爲除了HTTP狀態代碼(204)外沒有任何內容。

使用404來指示不成功的查找是一個明智的迴應。你應該使用它。