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: 'don@gmaill.com', password: 'test', password_confirmation: 'test')
Output:
(0.1ms) begin transaction
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'don@gmaill.com' LIMIT 1
(0.0ms) rollback transaction
=> #<User id: nil, name: "don", email: "don@gmaill.com", 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
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
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: 'don@gmaill.com', password: 'test', password_confirmation: 'test')
console > u.save!
To get rid of this error, first delete the record that exists in the DB
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.