0

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 Better Errors

finally it raises this error.

enter image description here

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
Nando
  • 747
  • 7
  • 23
  • 1
    Please consider posting your code as text. Posting it as images is not very helpful if someone wants to try it out. – Jesper Mar 04 '13 at 20:21

1 Answers1

5

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.

  • before this line `user ||= User.new # guest user` the variable user is nil, after it just a new User instance.. since i'm logged, the user must be my record isn't? – Nando Mar 04 '13 at 20:36
  • Nope. Undefined method name for NilClass that means user is nil – Ismael Abreu Mar 04 '13 at 20:36
  • It's line 10... The name method is being called on role, not user. –  Mar 04 '13 at 20:37
  • If user was nil the error would be "undefined method 'role' for nil::NilClass". –  Mar 04 '13 at 20:39
  • @NandoSousa The before_filter you get with Devise needs to run before the Cancan before_filters otherwise `current_user` will return nil. –  Mar 04 '13 at 20:48
  • @LeviStanley this error occurs only when i hit controller with put/post ajax request, any ajax trick or something? – Nando Mar 05 '13 at 13:32
  • @NandoSousa This might be useful: http://stackoverflow.com/questions/5126721/rails-not-reloading-session-on-ajax-post –  Mar 05 '13 at 17:09