用户的电子邮件参数未被保留到数据库中

时间:2015-07-20 20:59:50

标签: ruby-on-rails email ruby-on-rails-4

我在rails 4.1.8应用程序中创建了一个用户模型,其属性为emailpassword。我启动了rails控制台,user = User.new(email: "user@example.com" , password: "example")工作但user.save保存了密码并省略了电子邮件。下面是模型,迁移的数据库文件和rails控制台日志。

用户模型

class User < ActiveRecord::Base
    before_save {self.email = email.downcase! }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
    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

数据库文件(对于用户)

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
     t.string :email, unique: true
     t.string :password_digest

     t.timestamps null: false
   end
  end
end

RAILS CONSOLE LOG

<r.new(email: "user@example.com" , password: "example")
=> #<User id: nil, email: "user@example.com", password_digest:         "$2a$10$jxwd/oriT
z2HklHK4b4nf.P.DWb6s35YTO.EbYwup0I...", created_at: nil, updated_at: nil>
irb(main):008:0> user.save
(1.0ms)  BEGIN
User Exists (1.0ms)  SELECT  1 AS one FROM `users`  WHERE `users`.`email` =   'user@example.com' LIMIT 1
SQL (46.0ms)  INSERT INTO `users` (`created_at`, `password_digest`,  `updated_at`) VALUES ('2015-07-20 20:54:35', '$2a$10$jxwd/oriTz2HklHK4b4nf.P.DWb6s35YTO.Eb
Ywup0I.gMTOLSNKa', '2015-07-20 20:54:35')
(89.1ms)  COMMIT
=> true

USERS CONTROLLER

class UsersController < ApplicationController
  def new
  end

  private

    def user_params
      params.require(:user).permit(:email)
    end
end

查看日志中没有插入email参数;拜托,对此有任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

User模型中尝试以下操作:

before_save {self.email = email.downcase } # no "!" 

downcase!编辑调用它的变量,并且不会返回向下的字符串,除非有一些要小写的东西(例如,如果你在全部小写的电子邮件中使用它,它会返回nil并基于你的控制台输出,这是正在发生的事情)。仅downcase应该没问题。

downcase! on the API