См. Способности в базе данных и Способность для других пользователей из вики CanCan:
class Ability
include CanCan::Ability
def initialize(user)
can do |action, subject_class, subject|
user.permissions.find_all_by_action(aliases_for_action(action)).any? do |permission|
permission.subject_class == subject_class.to_s &&
(subject.nil? || permission.subject_id.nil? || permission.subject_id == subject.id)
end
end
end
end
РЕДАКТИРОВАНИЕ
Некоторые оптимизации загрузки:
class Ability
include CanCan::Ability
def initialize(user, context = nil)
if context.nil?
can do |action, subject_class, subject|
user.permissions.find_all_by_action(aliases_for_action(action)).any? do |permission|
permission.subject_class == subject_class.to_s &&
(subject.nil? || permission.subject_id.nil? || permission.subject_id == subject.id)
end
elsif context == :post
can :manage, Post, :id => y
elsif context == :users
can :manage, User, :id => x
end
...
А в контроллерах:
class UsersController
protected
def current_ability
Ability.new(current_user, :users)
class PostsController
protected
def current_ability
Ability.new(current_user, :posts)