回滚事务错误 - Rails

时间:2014-04-21 17:55:07

标签: ruby-on-rails transactions runtime-error

一些同学和我在课堂上的Rails应用程序中遇到了一些麻烦。每当我们尝试在rails控制台上为RoR应用程序使用User.create时,我们会在完成必要的表单后获得回滚事务。

有什么方法可以解决这个问题?这是错误:

rails console
Loading development environment (Rails 3.2.13)
irb(main):001:0> User.count
   (0.0ms)  SELECT COUNT(*) FROM "users"
=> 0
irb(main):002:0> User.create(name: "Mr Rush", email: "rush@example.com", password: "fubar", password_confirmation: "fubar")
   (0.0ms)  begin transaction
  User Exists (0.0ms)  SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('rush@example.com') LIMIT 1
   (0.0ms)  rollback transaction
=> #<User id: nil, name: "Mr Rush", email: "rush@example.com", created_at: nil, updated_at: nil, password_digest: "$2a$10$quwMA.4fcrBpg2sRy00qEOWrjHduAN0OZFvcXiCmNjUR...">
irb(main):003:0>

User.rb文件

class User < ActiveRecord::Base
  attr_accessible :email, :name, :password, :password_confirmation
  has_secure_password

  before_save { |user| user.email = user.email.downcase }

  validates :name, presence: true, length: {maximum: 30}
  VALID_EMAIL_REGEX = /\A[\w+\-\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format: {with: VALID_EMAIL_REGEX}, uniqueness: { case_sensitive: false }
  validates :password, presence: true, length: { minimum: 5 }
  validates :password_confirmation, presence: true
end

2 个答案:

答案 0 :(得分:2)

您的用户无法创建,因为电子邮件未通过格式验证。

有趣的是,它报告此错误,好像唯一性是导致问题的原因。您已将用户表显示为空,因此无法使唯一性约束失败。

要尝试的几件事情:

1)在控制台中试试这个:

user = User.new(name: "Mr Rush", email: "rush@example.com", password: "fubar", password_confirmation: "fubar")
user.valid?     <--- should give you false
user.errors     <--- should tell you the format of the email is incorrect

当我将presence与验证器中的任何其他内容结合使用时,我总是允许在以下验证中将该值设为空白;如果它是强制性的但缺失的,那么验证某些东西的格式或单一性是没有意义的。即。

validates :email, presence: true, format: {with: VALID_EMAIL_REGEX, allow_blank: true}, uniqueness: { case_sensitive: false, allow_blank: true }

这样做可能会也可能不会改变它认为真正的验证失败的原因。

2)修复正则表达式以进行电子邮件验证。通过正则表达式验证电子邮件地址有点争议,但你应该发现这样的东西会起作用:

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

您可以随时使用Rubular等网站试用正则表达式验证。

答案 1 :(得分:0)

User.create(name: "Mr Rush", email: "rush@example.com", password: "fubar", password_confirmation: "fubar")

在执行Michael Hartls Rails Tutorial时遇到此问题时,此示例将失败,因为密码fubar太短,设置为Listing 6.39中的minimum: 6。控制台在这里真的不够详细。

相关问题