最初我没有任何用户
控制台
User.all
User Load (4.6ms) SELECT "users".* FROM "users"
=> #<ActiveRecord::Relation []>
然后我从界面创建用户,如果我从控制台创建用户,我会得到相同的结果。
User.all
User Load (3.3ms) SELECT "users".* FROM "users"
=> #<ActiveRecord::Relation [#<User id: 1, name: "Kevin Orfas", email: nil, created_at: "2015-02-12 16:54:39", updated_at: "2015-02-12 16:54:39", password_digest: "$2a$10$cYywG.DMlgMOnK1AjutfKepTgVo.0uR63W3k5yA7ZQH...">]>
我应该在哪里集中精力查找错误?
UserController中
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
end
用户模型
class User < ActiveRecord::Base
before_save { self.email = email.downcase! }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[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, length: { minimum: 6 }
end
答案 0 :(得分:2)
downcase!
是一种非常奇怪的方法,与gsub!
非常相似,如果它不改变初始字符串,它会返回nil
。因此,如果您的电子邮件最初都是小写的,那么在nil
执行后,您最终会得到before_save
。将其更改为unbanged版本,一切正常:
before_save { self.email = email.downcase }
或者您可以直接在字符串上执行banged版本,而无需赋值:
before_save { self.email.downcase! }