2014-10-27 24 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来指示不成功的查找是一个明智的回应。你应该使用它。

相关问题