我尝试寻找答案,但他们都使用 User.new 等而不是创建。
当在控制台中使用具有有效属性的 User.create() 时,我得到一个使用 nil 作为 ID 和 nil 作为时间戳创建的用户。
这是我的用户模型。
class User < ApplicationRecord
attr_writer :name, :email
before_save {self.email = email.downcase}
validates :username, presence:true,
length: {maximum: 30},
uniqueness:true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence:true,
length: {maximum:200},
format: {with: VALID_EMAIL_REGEX},
uniqueness: {case_sensitive: false}
has_secure_password
validates :password, presence: true,
length: {minimum:6}
end
Run Code Online (Sandbox Code Playgroud)
在我正在使用的 Rails 控制台中
User.create(username:"oiuedhioj", email:"damhan@dagr.com",password:"test",password_confirmation:"test")
Run Code Online (Sandbox Code Playgroud)
并回来
<User id: nil, username: "Damhan", email: nil, created_at: nil, updated_at: nil, password_digest: "$2a$10$oGtRgcHigaHh/UCVX4QdM.AOgyGur8Oud5MyKZheUcQ...">
Run Code Online (Sandbox Code Playgroud)
尝试在 Rails 控制台中进行创建。
返回没有 ID 或时间戳的记录是无效记录的标志。
user = User.create(...)
user.valid?
=> false
user.errors.any?
=> true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2248 次 |
| 最近记录: |