ActiveAdmin - customising the records that are shown
So I've got an app where users (Devise) have the ability to see either all, or a subset of main model (in this case Schools), depending on whether the user is at branch, region or national level.
Branch belongs_to Region
School belongs_to Branch
What I'd like to do is to be able to wire up the permissions (maybe with a scope) in such a way as to be transparent开发者_StackOverflow社区 to ActiveAdmin. The user logs in to ActiveAdmin and is presented with a list of only the schools they're allowed to see.
So I guess this could either be an ActiveAdmin solution or something at a lower level.
Any ideas would be very welcome :)
You could set it up so a user has a polymorphic association to either a school, a branch or a region. If this association is nil it would mean that the user has access to everything (the national level you mentioned).
class User < ActiveRecord::Base
belongs_to :administrates, :polymorphic => true
end
class School < ActiveRecord::Base
belongs_to :branch
has_many :users, :as => :administrates
end
class Branch < ActiveRecord::Base
belongs_to :region
has_many :schools
has_many :users, :as => :administrates
end
class Region < ActiveRecord::Base
has_many :branches
has_many :users, :as => :administrates
end
You can't make it completely transparent to Active Admin as you have to tell Active Admin to use the particular scope. For this you should be able to get by with scope_to
inside your ActiveAdmin.register
blocks. You have to do a little magic to make scope_to
work with a polymorphic association, but it's doable:
ActiveAdmin.register School do
scope_to do
Class.new do
def self.schools
case current_user.administrates
when School
School.where(:id => current_user.administrates_id)
when Branch
School.where(:branch_id => current_user.administrates_id)
when Region
School.where(:branch_id => current_user.administrates.branches.map(&:id))
when NilClass
School.scoped
end
end
end
end
end
This basically means that each time Active Admin will load a school (or a list of schools on the index page), it will scope it through the anonymous class we created inside the scope_to
block.
You should be able to implement something similar on the Branch
and Region
models depending on your requirements.
You should be aware though, that there currently is an open issue when using scope_to
with regards to filters and forms showing resources outside the current users scope.
You also need authorization to limit users on a certain level to only see that level and below (e.g. users on a branch level should not have access to regions). For this you should use CanCan.
For info on how to integrate CanCan in Active Admin, see this or this.
精彩评论