2

I am trying to insert a new record into a SQLiteDB through my Rails console. Simply using User.create().

The row does not appear in my database.The message implies that a user exists, but calling User.first returns null and checking the database shows an empty table. What am I missing?

Input:

console > User.create(name: 'don', email: '[email protected]', password: 'test', password_confirmation: 'test')

Output:

   (0.1ms)  begin transaction
  User Exists (0.1ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = '[email protected]' LIMIT 1
   (0.0ms)  rollback transaction
 => #<User id: nil, name: "don", email: "[email protected]", created_at: nil, updated_at: nil, password_digest: "$2a$10$3EK3L932ryjrJPFIc4E0/uzavrpkWylDRzx4Wkdwzx8d..."> 

User Class:

class User < ActiveRecord::Base
    before_save { self.email = email.downcase }
    validates :name, presence: true, length: { maximum: 50 }

    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, 
                                        uniqueness: { case_sen,sitive: false }

    has_secure_password
    validates :password, length: { minimum: 6 }
end
3
  • Can you add the source of the User class? The 'User Exists' message doesn't mean that a user exists - it just means that the existence query is being run as part of the create process. Presumably in a validation step. There may be another validation that is failing. Source code would help. Commented Nov 5, 2013 at 5:19
  • @PeterGoldstein posted user class :) Commented Nov 5, 2013 at 5:29
  • ahhh the "test" password was too short my bad. Commented Nov 5, 2013 at 5:29

2 Answers 2

2

It's not persisting the User (you can tell by the rollback statement). Looks like it's failing a uniqueness validation on the email. You can look at the errors by calling errors.full_messages on the User you tried to create, or by using create! instead of create

Sign up to request clarification or add additional context in comments.

Comments

1

You are most likely validating uniqueness of email field. Hence ActiveRecord is issuing a select first to check if a record exist with the same email address, and finding one. Hence Create is not saving the new record to database.

But create returns the object anyway.

You can try this to verify this. Instead of create, try new followed by save!

console > u = User.new(name: 'don', email: '[email protected]', password: 'test', password_confirmation: 'test')
console > u.save!

To get rid of this error, first delete the record that exists in the DB

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.