[英]Rails - inserting a db row via console doesn't work
I am trying to insert a new record into a SQLiteDB through my Rails console. 我正在尝试通过Rails控制台将新记录插入SQLiteDB中。 Simply using
User.create()
. 只需使用
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. 该行未出现在我的数据库中。该消息表示某个用户存在,但调用
User.first
返回null
并检查数据库是否显示空表。 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). 它并没有持久化User(可以通过
rollback
语句看出来)。 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!
您可以通过在尝试创建的
User
上调用errors.full_messages
或使用create!
来查看错误create!
instead of create
而不是
create
You are most likely validating uniqueness of email
field. 您最有可能验证
email
字段的唯一性。 Hence ActiveRecord is issuing a select
first to check if a record exist with the same email address, and finding one. 因此,ActiveRecord首先发出一个
select
以检查是否存在具有相同电子邮件地址的记录,然后找到一个。 Hence Create
is not saving the new record to database. 因此,
Create
不会将新记录保存到数据库。
But create
returns the object anyway. 但是无论如何
create
返回对象。
You can try this to verify this. 您可以尝试执行此操作以验证这一点。 Instead of
create
, try new
followed by save!
代替
create
,先尝试new
然后再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 要消除此错误,请首先删除数据库中存在的记录
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.