Right now every time I change anything in user/edit the form requires the user to set a new password. I would like for it to require the current password (how can I ask for current password?) only incase a new password is entered. How can I achieve this, thanks a lot for this.
<%= form_for(@user, :html => {:multipart => true}) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :name, placeholder: :name %>
<%= f.text_field :email, placeholder: :email %>
<%= f.password_field :password, placeholder: "Enter new password" %>
<%= f.password_field :password_confirmation, placeholder: "Confirm new password" %>
<%= f.submit "Save changes", class: "btn btn-large btn-primary" %>
<% end %>
Using some info from rails_has_elegance and the web I came up with the following solution.
user/edit view:
<%= form_for(@user, :html => {:multipart => true}) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :name, placeholder: :name %>
<%= f.text_field :email, placeholder: :email %>
<%= password_field_tag :current_password, params[:current_password], placeholder: "Current password" %>
<%= f.password_field :password, placeholder: "New password (optional)" %>
<%= f.password_field :password_confirmation, placeholder: "Confirm new password" %>
<% end %>
User model:
validates :password, :on => :create
validates :password_confirmation, presence: true, :on => :update, :unless => lambda{ |user| user.password.blank? }
User controller:
def update
@user = User.find(params[:id])
user = User.find_by_email(current_user.email).try(:authenticate, params[:current_password])
if user && @user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in @user
redirect_to @user
else
flash.now[:error] = "Incorrect Current Password" unless user
sign_in @user
render 'edit'
end
end
You can add in your form old_password field
<%= f.password_field :old_password, placeholder: "Enter current password" %>
Add it to attr_accessible :old_password
and attr_accessor :old_password
And then you can validate it
validate :correct_old_pass, :on => :update
def correct_old_pass
errors[:old_password] << 'Incorrect pass' if your_check_method
end
You can create a separate form for changing password. And you can ask for current password just like you ask for a new one:
<%= form_for(@user, :html => {:multipart => true}) do |f| %>
<%= f.password_field :password, placeholder: "Enter current password" %>
<%= f.password_field :password, placeholder: "Enter new password" %>
<%= f.password_field :password_confirmation, placeholder: "Confirm new password" %>
<%= f.submit "Save changes", class: "btn btn-large btn-primary" %>
<% end %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With