Reputation: 747
i'm using Cancan + Devise in my rails app:
the problem happens when i try to update Comment record, i guess the user parameter of initialize method always is coming nil
even i'm logged:
Ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
unless user.nil?
if user.role.name == "admin"
can :manage, :all
elsif user.role.name == "atendimento"
can :manage, Comment
end
end
end
end
Better_errors
finally it raises this error.
everyone is facing this issue? anyone can help me?
Rails 3.2.8 Devise 2.1.0 CanCan 1.6.9 Ruby 1.9.3p385
Edit 1
CommentsController.rb
class CommentsController < ApplicationController
authorize_resource :only => [:index, :show,:new,:edit, :create,:update,:destroy, :approve, :moderate, :disapprove]
layout "admin"
Edit 2
Hey guys, CanCan works fine excerpt when controller receive ajax request..
Comments.js
var request = $.ajax({
url: url_to_request,
type: "PUT",
data: {id : id_to_send, answer : answer_to_send, question : question_to_send },
dataType: "json"
});
config/routes.rb
resources :comments do
member do
put 'approve'
put 'moderate'
put 'disapprove'
end
end
Upvotes: 0
Views: 876
Reputation:
It's not user
that is nil, it is user.role
.
You can use user.role.try(:name)
or ensure the role
method always returns an object that responds to name
.
Edit
Cancan uses the current_user
method on the controller. If that method returns nil, then user will be nil in your Ability file.
Make sure the Devise before_filter
runs before your Cancan before filters (like a call to load_and_authorize_resource
). If your user hasn't authenticated before Cancan starts trying to authorize, your user will be nil.
Upvotes: 5