我结合了上面的答案,得出了以下结论:
class ApplicationPolicy
attr_reader :user
def initialize(user)
@user = user
end
def self.permit(roles, options)
return if options[:to].none?
options[:to].each do |action|
define_method("#{action}?") do
return @user.roles? Array.wrap(roles) if options[:when].blank?
send(options[:when]) and @user.roles? Array.wrap(roles)
end
end
end
end
这允许人们像这样使用它:
class CommentPolicy < ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
@record = record
super(user)
end
permit %i[admin member], to: %i[show edit destroy update], when: :created_by_user
def created_by_user
@record.user == @user
end
end
和
permit :admin, to: %i[index update edit]
也可以
我的模型中的角色方法user
如下所示:
def roles?(user_roles)
user_roles.each do |role|
return true if role?(role)
end
false
end
def role?(role)
roles.any? { |r| r.name.underscore.to_sym == role }
end