Search code examples
ruby-on-railscancancancancan

CanCanCan. How to show only items that belong to that current logged in admin


I went through the Rails tutorial and Cancancan, ActiveAdmin documentation already. Now I stuck when trying to make the authorization that allow an admin_user that currently logged in only can see the notifications that belongs to that admin_user. Here is my code:

def initialize(admin_user)
    can :read, AdminUser, id: admin_user.id
    can :read, ActiveAdmin::Page, name: "Dashboard", namespace_name: "admin"
    can :read, Notification, id: notification.admin_user_id
end

I tried to play around with notification.admin_user_id part but I always get the error

undefined local variable or method 'notification'

Solution

  • not sure what's Notification but if let's say Notification belongs_to :admin and thus have admin_id column, I believe you should write it like that

    can :read, Notification, admin_id: admin_user.id

    In other words you shouldn't set up the ability on those notifications which have particular id. You should do that on the notifications that have particular admin_id or admin_user_id or user_id or whatever key that points to admin_user that the notification belongs to. This way you say actually "let admin_user be able to read the notifications which belong to him"