“exists?” method not working- trying to check if a user exists before saving to DB












1















I'm new to Rails, and am trying to create a signup form for my site. It works fine, with one exception- it saves users to the database without checking first to see if they exist. How can I check to make sure a user exists before I save it?



User controller:



class UsersController < ApplicationController
def new
@user = User.new
end

def create
@user = User.new(user_params)
if @user.exists?(:username) == false && @user.save(user_params)
session[:id] = @user.id
redirect_to posts_path
else
redirect_to '/signup'
end
end

def edit

end

def update
end

def show
end

def destroy
end

private

def user_params
params.require(:user).permit(:username, :jabber_id, :password)
end
end









share|improve this question




















  • 3





    How does your User model look like? How do you define that a user already exits – same email, same name?

    – spickermann
    Jan 2 at 16:56











  • Same username, though I might have the syntax wrong

    – jnjndjn
    Jan 2 at 16:57






  • 1





    You need to add a validation for uniqueness to your model as shown here: guides.rubyonrails.org/… Also, add a unique index to your username column on the database level via a migration as Rails validations are not full proof due to race conditions.

    – bkunzi01
    Jan 2 at 16:58
















1















I'm new to Rails, and am trying to create a signup form for my site. It works fine, with one exception- it saves users to the database without checking first to see if they exist. How can I check to make sure a user exists before I save it?



User controller:



class UsersController < ApplicationController
def new
@user = User.new
end

def create
@user = User.new(user_params)
if @user.exists?(:username) == false && @user.save(user_params)
session[:id] = @user.id
redirect_to posts_path
else
redirect_to '/signup'
end
end

def edit

end

def update
end

def show
end

def destroy
end

private

def user_params
params.require(:user).permit(:username, :jabber_id, :password)
end
end









share|improve this question




















  • 3





    How does your User model look like? How do you define that a user already exits – same email, same name?

    – spickermann
    Jan 2 at 16:56











  • Same username, though I might have the syntax wrong

    – jnjndjn
    Jan 2 at 16:57






  • 1





    You need to add a validation for uniqueness to your model as shown here: guides.rubyonrails.org/… Also, add a unique index to your username column on the database level via a migration as Rails validations are not full proof due to race conditions.

    – bkunzi01
    Jan 2 at 16:58














1












1








1








I'm new to Rails, and am trying to create a signup form for my site. It works fine, with one exception- it saves users to the database without checking first to see if they exist. How can I check to make sure a user exists before I save it?



User controller:



class UsersController < ApplicationController
def new
@user = User.new
end

def create
@user = User.new(user_params)
if @user.exists?(:username) == false && @user.save(user_params)
session[:id] = @user.id
redirect_to posts_path
else
redirect_to '/signup'
end
end

def edit

end

def update
end

def show
end

def destroy
end

private

def user_params
params.require(:user).permit(:username, :jabber_id, :password)
end
end









share|improve this question
















I'm new to Rails, and am trying to create a signup form for my site. It works fine, with one exception- it saves users to the database without checking first to see if they exist. How can I check to make sure a user exists before I save it?



User controller:



class UsersController < ApplicationController
def new
@user = User.new
end

def create
@user = User.new(user_params)
if @user.exists?(:username) == false && @user.save(user_params)
session[:id] = @user.id
redirect_to posts_path
else
redirect_to '/signup'
end
end

def edit

end

def update
end

def show
end

def destroy
end

private

def user_params
params.require(:user).permit(:username, :jabber_id, :password)
end
end






ruby-on-rails ruby ruby-on-rails-5






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 16:59







jnjndjn

















asked Jan 2 at 16:52









jnjndjnjnjndjn

63




63








  • 3





    How does your User model look like? How do you define that a user already exits – same email, same name?

    – spickermann
    Jan 2 at 16:56











  • Same username, though I might have the syntax wrong

    – jnjndjn
    Jan 2 at 16:57






  • 1





    You need to add a validation for uniqueness to your model as shown here: guides.rubyonrails.org/… Also, add a unique index to your username column on the database level via a migration as Rails validations are not full proof due to race conditions.

    – bkunzi01
    Jan 2 at 16:58














  • 3





    How does your User model look like? How do you define that a user already exits – same email, same name?

    – spickermann
    Jan 2 at 16:56











  • Same username, though I might have the syntax wrong

    – jnjndjn
    Jan 2 at 16:57






  • 1





    You need to add a validation for uniqueness to your model as shown here: guides.rubyonrails.org/… Also, add a unique index to your username column on the database level via a migration as Rails validations are not full proof due to race conditions.

    – bkunzi01
    Jan 2 at 16:58








3




3





How does your User model look like? How do you define that a user already exits – same email, same name?

– spickermann
Jan 2 at 16:56





How does your User model look like? How do you define that a user already exits – same email, same name?

– spickermann
Jan 2 at 16:56













Same username, though I might have the syntax wrong

– jnjndjn
Jan 2 at 16:57





Same username, though I might have the syntax wrong

– jnjndjn
Jan 2 at 16:57




1




1





You need to add a validation for uniqueness to your model as shown here: guides.rubyonrails.org/… Also, add a unique index to your username column on the database level via a migration as Rails validations are not full proof due to race conditions.

– bkunzi01
Jan 2 at 16:58





You need to add a validation for uniqueness to your model as shown here: guides.rubyonrails.org/… Also, add a unique index to your username column on the database level via a migration as Rails validations are not full proof due to race conditions.

– bkunzi01
Jan 2 at 16:58












4 Answers
4






active

oldest

votes


















4














A very simple validation would be something like this:



# in your user.rb
validates :username, uniqueness: true


You might want to ignore upper and lower case:



# in your user.rb
validates :username, uniqueness: { case_sensitive: false }


And change your create method to something like this:



def create 
@user = User.new(user_params)

if @user.save
session[:id] = @user.id
redirect_to posts_path
else
render :new
end
end


Furthermore, I suggest having a unique index on the database level too:



# in a migration
add_index :users, :username, unique: true





share|improve this answer


























  • May want to add presence: true as well.

    – tadman
    Jan 2 at 17:33











  • Would also be beneficial to add an example of modifying their controller. With this, they'll no longer need the exists? check because it should raise a validation error when they try to save.

    – Jay Dorsey
    Jan 2 at 18:52



















1














Use like this in the model file such as



validates_uniqueness_of :username #=> or specify :email or :name etc...





share|improve this answer



















  • 1





    The new form is validates :username, uniqueness: true. The old validates_X methods are still supported but aren't as flexible as the new ones.

    – tadman
    Jan 2 at 17:34



















0














As suggested, you should use model validation for something like this. However, here's why your code doesn't work.



The exists? method is to be used on the model class, not an instance of it for example:



Person.exists?(5)
Person.exists?(:name => "David")


The above is from the exists? docs






share|improve this answer































    0














    As almost people suggested you above and this is the best way to use uniqueness validation.



    But, If you want to give it a try with exists?
    You can do like,




    User.exists?(username: params[:username])







    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54010180%2fexists-method-not-working-trying-to-check-if-a-user-exists-before-saving-to%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4














      A very simple validation would be something like this:



      # in your user.rb
      validates :username, uniqueness: true


      You might want to ignore upper and lower case:



      # in your user.rb
      validates :username, uniqueness: { case_sensitive: false }


      And change your create method to something like this:



      def create 
      @user = User.new(user_params)

      if @user.save
      session[:id] = @user.id
      redirect_to posts_path
      else
      render :new
      end
      end


      Furthermore, I suggest having a unique index on the database level too:



      # in a migration
      add_index :users, :username, unique: true





      share|improve this answer


























      • May want to add presence: true as well.

        – tadman
        Jan 2 at 17:33











      • Would also be beneficial to add an example of modifying their controller. With this, they'll no longer need the exists? check because it should raise a validation error when they try to save.

        – Jay Dorsey
        Jan 2 at 18:52
















      4














      A very simple validation would be something like this:



      # in your user.rb
      validates :username, uniqueness: true


      You might want to ignore upper and lower case:



      # in your user.rb
      validates :username, uniqueness: { case_sensitive: false }


      And change your create method to something like this:



      def create 
      @user = User.new(user_params)

      if @user.save
      session[:id] = @user.id
      redirect_to posts_path
      else
      render :new
      end
      end


      Furthermore, I suggest having a unique index on the database level too:



      # in a migration
      add_index :users, :username, unique: true





      share|improve this answer


























      • May want to add presence: true as well.

        – tadman
        Jan 2 at 17:33











      • Would also be beneficial to add an example of modifying their controller. With this, they'll no longer need the exists? check because it should raise a validation error when they try to save.

        – Jay Dorsey
        Jan 2 at 18:52














      4












      4








      4







      A very simple validation would be something like this:



      # in your user.rb
      validates :username, uniqueness: true


      You might want to ignore upper and lower case:



      # in your user.rb
      validates :username, uniqueness: { case_sensitive: false }


      And change your create method to something like this:



      def create 
      @user = User.new(user_params)

      if @user.save
      session[:id] = @user.id
      redirect_to posts_path
      else
      render :new
      end
      end


      Furthermore, I suggest having a unique index on the database level too:



      # in a migration
      add_index :users, :username, unique: true





      share|improve this answer















      A very simple validation would be something like this:



      # in your user.rb
      validates :username, uniqueness: true


      You might want to ignore upper and lower case:



      # in your user.rb
      validates :username, uniqueness: { case_sensitive: false }


      And change your create method to something like this:



      def create 
      @user = User.new(user_params)

      if @user.save
      session[:id] = @user.id
      redirect_to posts_path
      else
      render :new
      end
      end


      Furthermore, I suggest having a unique index on the database level too:



      # in a migration
      add_index :users, :username, unique: true






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jan 2 at 22:14

























      answered Jan 2 at 16:59









      spickermannspickermann

      61.3k75880




      61.3k75880













      • May want to add presence: true as well.

        – tadman
        Jan 2 at 17:33











      • Would also be beneficial to add an example of modifying their controller. With this, they'll no longer need the exists? check because it should raise a validation error when they try to save.

        – Jay Dorsey
        Jan 2 at 18:52



















      • May want to add presence: true as well.

        – tadman
        Jan 2 at 17:33











      • Would also be beneficial to add an example of modifying their controller. With this, they'll no longer need the exists? check because it should raise a validation error when they try to save.

        – Jay Dorsey
        Jan 2 at 18:52

















      May want to add presence: true as well.

      – tadman
      Jan 2 at 17:33





      May want to add presence: true as well.

      – tadman
      Jan 2 at 17:33













      Would also be beneficial to add an example of modifying their controller. With this, they'll no longer need the exists? check because it should raise a validation error when they try to save.

      – Jay Dorsey
      Jan 2 at 18:52





      Would also be beneficial to add an example of modifying their controller. With this, they'll no longer need the exists? check because it should raise a validation error when they try to save.

      – Jay Dorsey
      Jan 2 at 18:52













      1














      Use like this in the model file such as



      validates_uniqueness_of :username #=> or specify :email or :name etc...





      share|improve this answer



















      • 1





        The new form is validates :username, uniqueness: true. The old validates_X methods are still supported but aren't as flexible as the new ones.

        – tadman
        Jan 2 at 17:34
















      1














      Use like this in the model file such as



      validates_uniqueness_of :username #=> or specify :email or :name etc...





      share|improve this answer



















      • 1





        The new form is validates :username, uniqueness: true. The old validates_X methods are still supported but aren't as flexible as the new ones.

        – tadman
        Jan 2 at 17:34














      1












      1








      1







      Use like this in the model file such as



      validates_uniqueness_of :username #=> or specify :email or :name etc...





      share|improve this answer













      Use like this in the model file such as



      validates_uniqueness_of :username #=> or specify :email or :name etc...






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Jan 2 at 16:59









      fool-devfool-dev

      5,73872542




      5,73872542








      • 1





        The new form is validates :username, uniqueness: true. The old validates_X methods are still supported but aren't as flexible as the new ones.

        – tadman
        Jan 2 at 17:34














      • 1





        The new form is validates :username, uniqueness: true. The old validates_X methods are still supported but aren't as flexible as the new ones.

        – tadman
        Jan 2 at 17:34








      1




      1





      The new form is validates :username, uniqueness: true. The old validates_X methods are still supported but aren't as flexible as the new ones.

      – tadman
      Jan 2 at 17:34





      The new form is validates :username, uniqueness: true. The old validates_X methods are still supported but aren't as flexible as the new ones.

      – tadman
      Jan 2 at 17:34











      0














      As suggested, you should use model validation for something like this. However, here's why your code doesn't work.



      The exists? method is to be used on the model class, not an instance of it for example:



      Person.exists?(5)
      Person.exists?(:name => "David")


      The above is from the exists? docs






      share|improve this answer




























        0














        As suggested, you should use model validation for something like this. However, here's why your code doesn't work.



        The exists? method is to be used on the model class, not an instance of it for example:



        Person.exists?(5)
        Person.exists?(:name => "David")


        The above is from the exists? docs






        share|improve this answer


























          0












          0








          0







          As suggested, you should use model validation for something like this. However, here's why your code doesn't work.



          The exists? method is to be used on the model class, not an instance of it for example:



          Person.exists?(5)
          Person.exists?(:name => "David")


          The above is from the exists? docs






          share|improve this answer













          As suggested, you should use model validation for something like this. However, here's why your code doesn't work.



          The exists? method is to be used on the model class, not an instance of it for example:



          Person.exists?(5)
          Person.exists?(:name => "David")


          The above is from the exists? docs







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 2 at 17:04









          Carl MarkhamCarl Markham

          6,17623265




          6,17623265























              0














              As almost people suggested you above and this is the best way to use uniqueness validation.



              But, If you want to give it a try with exists?
              You can do like,




              User.exists?(username: params[:username])







              share|improve this answer




























                0














                As almost people suggested you above and this is the best way to use uniqueness validation.



                But, If you want to give it a try with exists?
                You can do like,




                User.exists?(username: params[:username])







                share|improve this answer


























                  0












                  0








                  0







                  As almost people suggested you above and this is the best way to use uniqueness validation.



                  But, If you want to give it a try with exists?
                  You can do like,




                  User.exists?(username: params[:username])







                  share|improve this answer













                  As almost people suggested you above and this is the best way to use uniqueness validation.



                  But, If you want to give it a try with exists?
                  You can do like,




                  User.exists?(username: params[:username])








                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 2 at 17:51









                  2017kamb2017kamb

                  70111




                  70111






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54010180%2fexists-method-not-working-trying-to-check-if-a-user-exists-before-saving-to%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                      How to fix TextFormField cause rebuild widget in Flutter