我正在尝试使用 Rails 5 和 Mongoid 制作一个简单的用户注册功能。我的用户模型和控制器如下所示:
用户.rb
class User
include Mongoid::Document
include Mongoid::Timestamps
validates_presence_of :email
validates_uniqueness_of :email, case_sensitive: false
validates :password, presence: true, confirmation: true
validates_presence_of :password_confirmation
field :email, type: String
field :password, type: String
...
end
users_controller.rb
...
def create
@user = User.new(user_params)
if @user.save
json_response(nil, nil, :created)
else
json_response(@user.errors.full_messages, nil, :bad_request)
end
end
...
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :avatar)
end
现在我需要检查 password_confirmation 是否与密码相同,两个参数都是通过请求发送的,但是 password_confirmation 没有传递给新的用户对象,尽管它在强参数中被列入白名单:
日志:
Started POST "/users" for 127.0.0.1 at 2017-06-02 13:03:10 +0200
Processing by UsersController#create as JSON
Parameters: {"password"=>"[FILTERED]", email"=>"test@mail.com", "password_confirmation"=>"[FILTERED]", "user"=>{"email"=>"test@mail.com", "password"=>"[FILTERED]"}}
我不想添加
field :password_confirmation
到我的模型,它解决了这个问题。我只需要将属性设为虚拟并在验证后将其删除。我错过了什么或做错了什么?或者对此的正确态度是什么?