在Rails模型

时间:2016-09-23 17:08:44

标签: ruby-on-rails ruby activerecord rails-activerecord

我的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似乎已经确定,但是当我检查自己时,它是零。这也导致对象无法保存,因为它是零。更完整的日志版本是

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执行时,Insert,用户名和电子邮件都是nil,但我可以从debug puts语句中看出电子邮件和用户名存在并至少得到验证。也就是说,即使我完全删除了验证,我也遇到了这个问题。

3 个答案:

答案 0 :(得分:0)

你试过这个吗?

self.email.downcase! if email.present?

答案 1 :(得分:0)

@arieljuod通过建议我使用自定义setter而不是在验证之前尝试更改内容来解决这个问题。问题解决了虽然我不完全理解为什么其他方式不起作用,即使它不是“最佳”

def username=(value)
  self[:username] = value.downcase
end

def email=(value)
  self[:email] = value.downcase
end

答案 2 :(得分:-1)

您需要在模型上调用save。所以只需在模型上调用self.save即可。