2
votes

How can i use scoping with active admin & cancan. I have admin users & those have (has_one) relation with institution and institution has many profiles Now when admin user login then i want display all profiles which has same institution.

Doesn't find following link much helpful.

http://activeadmin.info/docs/2-resource-customization.html#scoping_the_queries

1

1 Answers

4
votes

if you just do simply this, do you get a problem?

# ability.db

def initialize(user)
  case
    # ...
    when user.super_admin?
      can :manage, :all
    when user.admin?
      can :manage, Profile, :institution_id => user.institution.id
    # 
    # ...
end

this will allow: Profile.accessible_by(current_user), which here is same as current_user.profiles

class AdminUser
  has_one :institution
  has_many :profiles, :through => :institution
end

ActiveAdmin.register Profile do
  scope_to :current_user #here comes the variable which set in initializer
end

if you want superadmin to access all posts, you can use the :association_method option

ActiveAdmin.register Profile do
  scope_to :current_user, :association_method => :admin_profiles
end 

# in class User
def admin_profiles
  if super_admin?
    Profile.unscoped
  else
    profiles
  end
end

A tricky solution could generalize this and use a delegator class as proxy to unscope all models for superadmins. i can spell out on request.