ajax检查邮件是否已经存在Ruby on Rails

时间:2022-09-25 23:51:11

What im trying to do:
1.Send data to the server and check if that email exist in the database and return true if exist and false if it does not exist What I have done so far: I created this js code that fires on change keyup and paste.

我想做的是:1。向服务器发送数据并检查该邮件是否存在于数据库中,如果存在则返回true;如果不存在则返回false。

$("#user_email").on('change keyup paste',function(){
        console.log("change?");
    $.post('/checkEmail?email='+$("#user_email").val(),function(data){

    }); 
   //this request results to 404 not found.
});

I have this on rake routes

这是耙路

checkEmail POST   /checkemail(.:format)        user#emailcheck

routes.rb

routes.rb

Rails.application.routes.draw do
  get 'products/index'

  get 'home/index'

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  # root 'welcome#index'
  root 'home#index'

  resources :users, :products

  # resources :users do
  #   resources :products
  # end

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'
  post '/checkemail' => 'users#emailcheck', as: :checkEmail
  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end

my users_controller.rb

我users_controller.rb

 def emailcheck
        @user = User.search(params[:email])
 end

user.rb mode

用户。rb模式

class User < ActiveRecord::Base
    validates :terms_of_service, acceptance:{ :accept => '0'}
     validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i

     validates_presence_of :email,:password,:firstname,:lastname,:address,:phonenumber
    has_many :products

    def self.search(email)
        if email
            where('email = ?',email).first
        end

    end
end

I dont know how to point how to use the method inside my users_controller using ajax ang create a response of true or false base on the results.can some one help me do this because im relatively new to ruby on rails

我不知道如何在users_controller中使用ajax ang创建基于结果的真或假响应。有人能帮我做一下吗?因为我对ruby on rails还比较陌生

Error Log

错误日志

POST http://localhost:3000/checkemail?email=sample 404 (Not Found)jQuery.ajaxTransport.send @ jquery.self-d03a5518f45df77341bdbe6201ba3bfa547ebba8ed64f0ea56bfa5f96ea7c074.js?body=1:9660jQuery.extend.ajax @ jquery.self-d03a5518f45df77341bdbe6201ba3bfa547ebba8ed64f0ea56bfa5f96ea7c074.js?body=1:9211jQuery.each.jQuery.(anonymous function) @ jquery.self-d03a5518f45df77341bdbe6201ba3bfa547ebba8ed64f0ea56bfa5f96ea7c074.js?body=1:9357(anonymous function) @ user.self-4e8aa3f9430109eadc33d5aa4fd038041afbf947d7c95717d55caf908ce3f0df.js?body=1:5jQuery.event.dispatch @ jquery.self-d03a5518f45df77341bdbe6201ba3bfa547ebba8ed64f0ea56bfa5f96ea7c074.js?body=1:4666jQuery.event.add.elemData.handle @ jquery.self-d03a5518f45df77341bdbe6201ba3bfa547ebba8ed64f0ea56bfa5f96ea7c074.js?body=1:4334

rails console

rails控制台

Started POST "/checkemail?email=d" for 127.0.0.1 at 2015-07-23 15:18:21 +0800

ActionController::RoutingError (uninitialized constant UserController):
  activesupport (4.2.3) lib/active_support/inflector/methods.rb:261:in `const_get'
  activesupport (4.2.3) lib/active_support/inflector/methods.rb:261:in `block in constantize'
  activesupport (4.2.3) lib/active_support/inflector/methods.rb:259:in `each'
  activesupport (4.2.3) lib/active_support/inflector/methods.rb:259:in `inject'
  activesupport (4.2.3) lib/active_support/inflector/methods.rb:259:in `constantize'
  actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:72:in `controller_reference'
  actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:62:in `controller'
  actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:41:in `serve'
  actionpack (4.2.3) lib/action_dispatch/journey/router.rb:43:in `block in serve'
  actionpack (4.2.3) lib/action_dispatch/journey/router.rb:30:in `each'
  actionpack (4.2.3) lib/action_dispatch/journey/router.rb:30:in `serve'
  actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:821:in `call'
  rack (1.6.4) lib/rack/etag.rb:24:in `call'
  rack (1.6.4) lib/rack/conditionalget.rb:38:in `call'
  rack (1.6.4) lib/rack/head.rb:13:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/flash.rb:260:in `call'
  rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.2.3) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.2.3) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'
  activerecord (4.2.3) lib/active_record/migration.rb:377:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.2.3) lib/active_support/callbacks.rb:84:in `run_callbacks'
  actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  web-console (2.2.1) lib/web_console/middleware.rb:39:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.3) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.2.3) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.2.3) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.2.3) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
  rack (1.6.4) lib/rack/runtime.rb:18:in `call'
  activesupport (4.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  rack (1.6.4) lib/rack/lock.rb:17:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/static.rb:116:in `call'
  rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
  railties (4.2.3) lib/rails/engine.rb:518:in `call'
  railties (4.2.3) lib/rails/application.rb:165:in `call'
  rack (1.6.4) lib/rack/lock.rb:17:in `call'
  rack (1.6.4) lib/rack/content_length.rb:15:in `call'
  rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'
  /home/admin-new/.rbenv/versions/2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
  /home/admin-new/.rbenv/versions/2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
  /home/admin-new/.rbenv/versions/2.2.2/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'

1 个解决方案

#1


6  

It is a typo, just make it like this and try:

这是一个打印错误,就像这样试着:

$("#user_email").on('change keyup paste',function(){
        console.log("change?");
    $.post('/checkemail?email='+$("#user_email").val(),function(data){

    });
});

And in the routes make it to this:

在这条路线中

post '/checkemail', to: 'users#emailcheck'

Or whatever you have written make this: user#emailcheck to users#emailcheck as controllers are always in plural form.

或者无论你写了什么:用户#emailcheck给用户#emailcheck,因为控制器总是以复数形式存在。

In your users_controller make it:

在users_controller中:

def emailcheck
  @user = User.search(params[:email])
  respond_to do |format|
    format.json {render :json => {email_exists: @user.present?}} #sir Deep suggestion to return true or false for email_exists or the code below
   # format.json {render :json => @user} #this will output null if email is not in the database
  end
end

As you need json response.

需要json响应。

Hope this helps.

希望这个有帮助。

#1


6  

It is a typo, just make it like this and try:

这是一个打印错误,就像这样试着:

$("#user_email").on('change keyup paste',function(){
        console.log("change?");
    $.post('/checkemail?email='+$("#user_email").val(),function(data){

    });
});

And in the routes make it to this:

在这条路线中

post '/checkemail', to: 'users#emailcheck'

Or whatever you have written make this: user#emailcheck to users#emailcheck as controllers are always in plural form.

或者无论你写了什么:用户#emailcheck给用户#emailcheck,因为控制器总是以复数形式存在。

In your users_controller make it:

在users_controller中:

def emailcheck
  @user = User.search(params[:email])
  respond_to do |format|
    format.json {render :json => {email_exists: @user.present?}} #sir Deep suggestion to return true or false for email_exists or the code below
   # format.json {render :json => @user} #this will output null if email is not in the database
  end
end

As you need json response.

需要json响应。

Hope this helps.

希望这个有帮助。