I have a User model with name and password attributes. When the user clicks on 'Edit' I want just the name field to be editable and validated but not the password field. And vice versa for when the user clicks on 'Reset Password'. I think my main problem is how do I turn password validation off during the name field edit and how do I turn off name validation during the password edit?
edit.html.erb
<%= form_for @user, html: { class: "form_settings" } do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<p><span><%= f.label :name %></span>
<%= f.text_field :name %>
</p>
<p style="padding-top: 15px"><span> </span>
<%= f.submit "Submit", class: "submit" %>
</p>
<% end %>
reset_password.html.erb
<%= form_for @user, html: { class: "form_settings" } do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<p><span><%= label_tag :old_password, "Current Password" %></span>
<%= password_field_tag :old_password %>
</p>
<p><span><%= f.label :password %></span>
<%= f.password_field :password %>
</p>
<p><span><%= f.label :password_confirmation %></span>
<%= f.password_field :password_confirmation %>
</p>
<p style="padding-top: 15px"><span> </span>
<%= f.submit "Submit", class: "submit" %>
</p>
<% end %>
users_controller.rb
def update
@user = User.find(params[:id])
if params[:old_password]
if @user.authenticate(params[:old_password])
@user.update_attributes(password: params[:user][:password])
flash[:success] = "Password has been updated"
redirect_to @user
else
flash.now[:error] = "Current password is incorrect"
render :reset_password
end
elsif @user.update_attributes(params[:user])
flash[:success] = "User name updated"
redirect_to @user
else
render :edit
end
end
My other problem is that password and password_confirmation validation is not working. This is what I have in the model:
validates :password, presence: true, confirmation: true
UPDATE Got the password to reset and the validation working with this code:
def update
@user = User.find(params[:id])
if params[:old_password]
if @user.authenticate(params[:old_password])
if params[:user][:password] == params[:user][:password_confirmation]
@user.update_attributes(password: params[:user][:password])
flash[:success] = "Password has been updated"
redirect_to @user
else
flash.now[:error] = "Passwords don't match"
render :reset_password
end
else
flash.now[:error] = "Current password is incorrect"
render :reset_password
end
elsif @user.update_attributes(params[:user])
flash[:success] = "User name updated"
redirect_to @user
else
render :edit
end
end
But it seems too complicated for me. Anyone see an easier solution?
But I still have the problem of editing the name field. It's saying password can't be blank.