Rails 5 + Mongoid virtual attribute

521 views Asked by At

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"=>"[email protected]", "password_confirmation"=>"[FILTERED]", "user"=>{"email"=>"[email protected]", "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?

1

There are 1 answers

2
Mateus Pinheiro On

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.