I'm Using Devise in my Rails 3.0.9 application for User Authentication. As I wanted to be able to manage Users, I created the following Users Controllers:
class UsersController < ApplicationController
def index
@users = User.all
end
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = "Successfully created User."
redirect_to users_path
else
render :action => 'new'
end
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
params[:user].delete(:password) if params[:user][:password].blank?
params[:user].delete(:password_confirmation) if params[:user][:password].blank? and params[:user][:password_confirmation].blank?
if @user.update_attributes(params[:user])
if current_user.update_with_password(params[:user])
sign_in(current_user, :bypass => true)
end
flash[:notice] = "Successfully updated User."
redirect_to users_path
else
render :action => 'edit'
end
end
def destroy
@user = User.find(params[:id])
if @user.destroy
flash[:notice] = "Successfully deleted User."
redirect_to users_path
end
end
end
I this works for showing, creating and deleting Users, but I have run into a problem when updating the passwords.
When I Update the password for the currently logged in account it automatically logs me out.
In the controller I tried to fix this using: (you can see it in the code above)
if current_user.update_with_password(params[:user])
sign_in(current_user, :bypass => true)
end
But that gives me this error ->
undefined method `update_with_password' for nil:NilClass
What I'm really looking for, is the ability to update any accounts password, without logging them out ( as admins have ability to change regular users password ).
It is not necessary to write
This code in the controller
if current_user.update_with_password(params[:user])
sign_in(current_user, :bypass => true)
end
Instead you should go ahead with below one
if @user.update_attributes(params[:user])
sign_in(current_user, :bypass => true)
redirect_to users_path
end
cheers :)
The easiest way to do this is call
sign_in(current_user, :bypass => true)
After the update.
This is what my controller action looks like:
def update_password
if current_user.update_with_password(params[:user])
sign_in(current_user, bypass: true)
flash[:notice] = "Updated Password Successfully"
else
flash[:error] = "There was an error updating your password, please try again."
end
end
I think this is basically what @challenge proposed but I just wanted to make a little cleaner and easier to understand.
精彩评论