Search code examples
ruby-on-railsrubydevisejquery-validate

how to check email exist in rails, devise gem


I am a beginner at Ruby.

I have created my website using Rails, and am using the Devise gem to create users. In sign_up. users/registrations/new.html.erb I have:

<div class="form-group">
    <%= f.label :"Email address  *" %>
    <%= f.email_field :email, class: "form-control" , placeholder: "Enter your email", name: "email" %>
</div>

And I am using a jQuery validation plugin on my validation form, adding a new rule:

jQuery.validator.addMethod("checkAlreadyEmail", function( value, element ) {
  var unavailable = true;
  $.ajax({
    url : '/users/check_already_email',
    type : "POST",
    async: false,
    data : 'email =' + value,
    dataType : "json",
    success : function(data) {
      if(data.available == true){
        unavailable = false;
      }
    }
  });
  return unavailable;
}, "This email is already taken");

$("#new_user").validate({
  rules: {
    email: {
      required: true,
      email: true,
      checkAlreadyEmail: true,
      },}
messages: {
    email: {
      required: "Please enter your email",
      email: "Please enter valid email address",
      checkAlreadyEmail: "This email is already taken",
    },},})

In users/registrations_controller.rb I have

def check_already_email
    @email = users.search(params[:email])
  end

What is next ? I am sorry, this is the first time I am asking a question on StackOverflow.


Solution

  • How the process works is,

    1 - User fill the form

    2 - User click submit button

    3 - JQuery validator will validate the form depending on your rules defined, and if everything if ok submit the form (which will create a user in the DB)

    as per your code, you should add a route in config/routes.rb to handle the request check_already_email. something like..

    #config/routes.rb
    get "registrations/check_already_email" =>"registrations#check_email", as: :check_email
    

    Following is almost the same thing which you try to do, have a look