0

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?

1 Answers1

0

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.

Mateus Pinheiro
  • 870
  • 2
  • 12
  • 20
  • unfortunatelly this does not help, it seems that `params.require(:user).permit(...)` can only work with those attributes defined by `field` and it ignores `attr_accessor` – David Bambušek Jun 20 '17 at 12:17
  • Well, as a last resort you can add it as a field, but prevent it from saving by creating a before_save filter to nil it. It's ugly but will work. – Mateus Pinheiro Jun 21 '17 at 11:59