[英]Why is my user being created through Rails console, but no email attribute being stored in the database?
我在railstutorial.org上關注Rails教程。 當前,我將要完成第6章。當我通過Rails控制台創建新用戶時,該用戶已在數據庫中創建,但email屬性設置為nil
。 當我直接向用戶分配電子郵件時,它在內存中被更改,但是當我通過save
方法將其save
以將其持久save
在數據庫中時,出現以下錯誤:
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER(?) AND "users"."id" != ? LIMIT
為什么將其保存在內存中而不保存在數據庫中?
我嘗試使用rails db:migrate
數據庫。 並刪除所有用戶,以防其他用戶使用相同的電子郵件(因為對於郵件的唯一性存在約束或驗證規則)。 仍然會出現相同的錯誤。
這是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
這是用戶模型:
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
經過數小時的閱讀,事實證明我只需要使用rails db:migrate:reset
。 而且有效。 顯然,仍然存在非唯一郵件或其他內容。 我沒有完全理解為什么會發生錯誤,如果有人可以給我更好地了解Rails框架的內部功能,我將不勝感激,因為我也是這個新手。 感謝您的支持。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.