Ruby on Rails。无法在数据库中创建记录

时间:2015-06-10 11:13:41

标签: mysql ruby-on-rails ruby database

在数据库中创建新记录时遇到问题 模特目前看起来像这样:

class User < ActiveRecord::Base
      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i

      before_save {!self.email.downcase}

      validates :name, presence: true, length: {maximum: 50}
      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

最初尝试从代码创建记录,但没有任何错误就失败了。 作为下一步,我尝试在控制台中手动创建记录,但仍然具有相同的结果。没有错误可用。从验证中删除验证,重新设置数据库,重新启动服务器或排除电子邮件REGEXP(对我来说总是麻烦的来源)并没有帮助......

user = User.new(name: "Fedor U", email: "fredy@mail.ru", password: "asdzxc123", password_confirmation: "asdzxc123")
=> #<User id: nil, name: "Fedor U", email: "fredy@mail.ru", created_at: nil, updated_at: nil, password_digest: "$2a$10$89SABxu2lOo3gj6DiqLZEOlSheAfEk0ex.5GYmJ5e8i...">

>> user.save
(0.2ms)  begin transaction
User Exists (0.2ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('fredy@mail.ru') LIMIT 1
(0.1ms)  rollback transaction
=> false
>> user.errors.any?
=> false
user.errors.full_messages
=> []

>> user.save(validation: false)
(0.1ms)  begin transaction
User Exists (0.2ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('fredy@mail.ru') LIMIT 1
(0.1ms)  rollback transaction
=> false

任何想法我做错了什么? Rails 4.2.0,bcrypt 3.1.7。
数据库目前是空的。

1 个答案:

答案 0 :(得分:2)

!self.email.downcase将返回truefalse

使用self.email.downcase!将电子邮件更改为小写。