我已经安装了CanCan并在Gemfile中添加了行gem 'cancan'
。跑bundle
。
我使用代码创建了app/models/ability.rb
:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, :all
end
end
end
安装并插入ActiveAdmin 和设计。
我将if cannot?
添加到app / admin / codes.rb:
ActiveAdmin.register Code do
if cannot? :manage, Code
flash[:notice] = "Access denied"
redirect_to '/'
end
index do
column :id
column :title
column :author
column :created_at
column :updated_at
column :language
default_actions
end
end
rails无法启动服务器或打开rails console:
app/admin/codes.rb:2:in `block in <top (required)>': undefined method `cannot?'
for #<ActiveAdmin::ResourceDSL:0x4ae7fe8> (NoMethodError)
我该如何解决?
答案 0 :(得分:2)
cancan方法被添加到所有控制器和模型中,而不是其他任何内容,因此您需要在ActiveAdmin类中手动包含cancan方法。请考虑遵循以下模式:
https://github.com/ryanb/cancan/blob/master/lib/cancan/controller_additions.rb
类似于include CanCan::ControllerAdditions
答案 1 :(得分:1)
我做到了。
我附加了执行到控制器上下文中的代码:
controller do
before_filter :check_admin
def check_admin
if cannot? :manage, Code
flash[:alert] = "Access denied!"
redirect_to '/admin'
end
end
end