【发布时间】:2016-09-23 17:08:43
【问题描述】:
我的 Rails 用户模型中有一个方法,如下所示:
def prep_data
if email.present?
self.email = email.downcase
end
if username.present?
self.username = username.downcase
end
puts "***********************"
puts self.email
puts self.inspect
puts "***********************"
end
当我运行它时,我得到:
***********************
john@me.com
#<User id: nil, username: nil, email: nil, password_salt: nil, password_digest: nil, created_at: nil, updated_at: nil>
***********************
我不知道为什么 self.email 似乎已设置,但是当我检查 self 时,它是 nil。这也导致对象不保存,因为它为零。更完整的日志版本是
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"7ocuB7GiyPjMZ84SHKo9CDSPjY8uOdtDc5A9wr+stzTPrIHnvfxAkdp1HxWActd07ZWzJVEBH43A3V/4sX1ixg==", "user"=>{"username"=>"John", "email"=>"John@me.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create User"}
(0.0ms) begin transaction
***********************
john@me.com
#<User id: nil, username: nil, email: nil, password_salt: nil, password_digest: nil, created_at: nil, updated_at: nil>
***********************
***********************
john@me.com
#<User id: nil, username: nil, email: nil, password_salt: "$2a$10$T92qOVBwjGm4t550POLVHu", password_digest: "$2a$10$T92qOVBwjGm4t550POLVHuXhss6lniJJekxMbeKR/yU...", created_at: nil, updated_at: nil>
***********************
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE "users"."username" = 'john' LIMIT 1
User Exists (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'john@me.com' LIMIT 1
SQL (0.7ms) INSERT INTO "users" ("password_salt", "password_digest", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["password_salt", "$2a$10$T92qOVBwjGm4t550POLVHu"], ["password_digest", "$2a$10$T92qOVBwjGm4t550POLVHuXhss6lniJJekxMbeKR/yU.79uMqtZJa"], ["created_at", "2016-09-23 17:51:31.692923"], ["updated_at", "2016-09-23 17:51:31.692923"]]
SQLite3::ConstraintException: NOT NULL constraint failed: users.username: INSERT INTO "users" ("password_salt", "password_digest", "created_at", "updated_at") VALUES (?, ?, ?, ?)
最终目标是让它真正保存。您可以看到,当 Rails 执行插入操作时,用户名和电子邮件为 nil,但我可以从调试 puts 语句中得知电子邮件和用户名存在并且至少正在验证。也就是说,即使我完全删除了验证,我也有这个问题。
【问题讨论】:
-
你怎么知道电子邮件存在?
-
这太奇怪了,你的代码有别的东西弄乱了。我看到你只是在清理用户值,你可能想在自定义设置器中这样做,检查这个stackoverflow.com/questions/39665490/…。即使您不需要使用自定义设置器,您也应该尝试解决这个特定问题,因为它稍后会在其他地方爆炸。
标签: ruby-on-rails ruby activerecord rails-activerecord