简体   繁体   中英

Why is my user being created through Rails console, but no email attribute being stored in the database?

I am following the Rails tutorial at railstutorial.org. Currently I am about to finish Chapter 6. When I go to create a new user through rails console, the user is created in the database but the email attribute is set to nil . When I assign directly an email to the user, it is changed in memory but when I go and save it through the save method to persist it in the database, the following error shows up:

User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER(?) AND "users"."id" != ? LIMIT

Why does it save in memory but not in the database?

I tried remigrating the database with rails db:migrate . And deleting all users in case there were some other users with the same email (as there is a constraint or validation rule for the uniqueness of the mail). Still get the same error.

This is the schema.rb

ActiveRecord::Schema.define(version: 2019_01_13_035531) do

create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "password_digest"
    t.index ["email"], name: "index_users_on_email", unique: true
end

end

This is the user model:

class User < ApplicationRecord
    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, length: { maximum: 255 },
                      format: { with: VALID_EMAIL_REGEX },
                      uniqueness: { case_sensitive: false }
    has_secure_password
    validates :password, presence: true, length: { minimum: 6 }
end

After hours of reading, it turned out that I had just to rails db:migrate:reset . And it worked. Apparently, there was still a non unique mail or something. I didn't get to understand fully why did the error happened and if someone can give me a better insight of the inner functioning of the rails framework would be much appreciated as I am new to this too. Thank your for your kind support.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM