Password confirmation in Rails 5

10,029

You need to add password_confirmation to user_params in the controller.

I.e.

def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
Share:
10,029
gdfgdfg
Author by

gdfgdfg

Updated on June 15, 2022

Comments

  • gdfgdfg
    gdfgdfg almost 2 years

    This is my view:

    <%=form_for [:admin, @user] do |f|%>
    
        <ul>
            <% @user.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
        </ul>
    
        <%=f.label :name %>
        <%=f.text_field :name %>
    
    
        <%=f.label :email %>
        <%=f.text_field :email %>
    
        <%=f.label :password %>
        <%=f.password_field :password %>
    
        <%=f.label :password_confirmation %>
        <%=f.password_field :password_confirmation%>
    
        <%=f.submit "Submit" %>
    <%end%>
    

    Controller code for adding user:

    def create
        @user = User.new(user_params)
    
        if @user.save
            redirect_to admin_users_path
        else
            render 'new'
        end
    end
    
    private
    def user_params
        params.require(:user).permit(:name, :email, :password)
    end
    

    These are validations in the model:

    validates :name, presence: true
    validates :email, presence: true
    validates :password, presence: true
    validates :password, confirmation: { case_sensitive: true }
    

    But confirmation password doesn't work.

    Validation works for all (they are required) form elements, except second password input - password_confirmation which can be different from first password input.

    User is added to the database even if second password input is empty, because in the validation rules, there is no rule for that .

    What am I doing wrong ?