MSK MSK - 7 months ago 17
Ruby Question

Getting a validating error of password which is not present in the edit profile page. Ruby on rails

I want to update users attributes without password in devise. The case is, when i hit update profile after editing the profile, I am getting a validating error of password which is not present in the edit profile page ! How could I do this with devise?

models/user.rb

validates :password, presence:true, :format => { :with => /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/,
:message => "Password should contain at least 6 characters, one upper case, one lower case and one numeric." }


My application controller is,

class ApplicationController < ActionController::Base

protect_from_forgery with: :exception

before_action :configure_permitted_paramters, if: :devise_controller?

protected
def configure_permitted_paramters
devise_parameter_sanitizer.for(:sign_up) << :fullname
devise_parameter_sanitizer.for(:account_update) << :fullname << :phone_number << :description << :email << :password << :gender << :current_password << :avatar
end
end


My registrationscontroller is,

class RegistrationsController < Devise::RegistrationsController
protected
def update_resource(resource, params)
resource.update_without_password(params)
end
end


My edit.html/registrations is,

<div class="row">
<label class="col-xs-4" for="fullname">Fullname</label>
<div class="col-xs-8">
<%= f.text_field :fullname, autofocus: true, :placeholder => "Full Name", :class => 'form-control' %>
</div>
</div></br></br>
<div class="row">
<label class="col-xs-4" for="date_of_birth">Date of Birth</label>
<div class="col-xs-8">
<%= f.date_select :date_of_birth, order: [:day, :month, :year], :start_year=>1910 %>
</div>
</div>
<div class="row">
<label class="col-xs-4" for="gender">Gender</label>
<div class="col-xs-8">
<%= f.check_box :gender, {}, false %> <%= f.label :gender, "Female" %>
<div class="col-xs-4">
<%= f.check_box :gender, {}, true %> <%= f.label :gender, "Male" %>
</div>
</div>
</div>


My routes.rb is,

Rails.application.routes.draw do

root 'pages#home'

devise_for :users,
:path => '',
:path_names => {:sign_in => 'login', :sign_out => 'logout', :edit => 'profile'},
:controllers => {:registrations => 'registrations'}

resources :users

end


When i hit update profile then it is showing,
"Password should contain at least 6 characters, one upper case, one lower case and one numeric."

the password field is not present in the edit registrations form as i want to update without password.

Answer

To skip a validation in update, Just give option on: :update. This should allow to update without password required. lmk...

  validates :password, length: { in: 8..16 }, on: :create
  validates :password, length: { in: 8..16 }, on: :update, allow_blank: true