I use Devise and CanCan to authenticate users and administer roles that restrict access to parts of my Rails 4 application to specific users.
I am having problems updating my user. The update works fine and the user object in db is updated as it should, but my user session is lost in the next redirect_to action of my user action. current_user becomes nil , which means that CanCan restricts access to user action.
Why does current_user become nil after updating, when it does not happen with other actions (for example, create, destroy, etc.)?
These are the device settings in my user model:
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]
This is my users_controller.rb method:
class UsersController < ApplicationController load_and_authorize_resource before_filter :authenticate_user! def update @user = User.find(params[:id]) if params[:user][:password].blank? params[:user].delete(:password) end respond_to do |format| if @user.update_attributes(user_params) format.html { redirect_to user_path, :notice => 'User was successfully updated.' } format.json { head :ok } else format.html { render :action => "edit" } format.json { render :json => @user.errors, :status => :unprocessable_entity } end end end end
And this is my able.rb file:
class Ability include CanCan::Ability def initialize(user) user ||= User.new
source share