I am trying to make a simple user signup functionality with Rails 5 and Mongoid. My user model and controller look like this:
user.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
Now I need to check if the password_confirmation is the same as password, both params are send through the request, but password_confirmation is not passed to the new user object, altought it is whitelisted in strong parameters:
log:
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]"}}
I don't want to add
field :password_confirmation
to my model, which solves this problem. I just need to make the attribute virtual and get rid of it after validation. What am I missing or doing wrong? Or what is the correct attitude to this?
In your model, add it as an attr_acessor
Class User
...
field :email, type: String
field :password, type: String
attr_accessor :password_confirmation
...
end
You'll be able to access it, but it will not be persisted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.