2

我已经安装了 CanCangem 'cancan'并向 Gemfile 添加了行。冉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

ActiveAdminDevise已安装并插入。

我添加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 控制台:

app/admin/codes.rb:2:in `block in <top (required)>': undefined method `cannot?'
for #<ActiveAdmin::ResourceDSL:0x4ae7fe8> (NoMethodError)

我该如何解决?

4

2 回答 2

2

cancan 方法被添加到所有控制器和模型中,而不是其他任何东西,因此您需要在 ActiveAdmin 类中手动包含 cancan 方法。考虑遵循此处的模式:

https://github.com/ryanb/cancan/blob/master/lib/cancan/controller_additions.rb

有类似的东西include CanCan::ControllerAdditions

于 2012-08-10T21:10:46.497 回答
1

我做到了。
我已经附加了在控制器上下文中执行的代码:

  controller do
    before_filter :check_admin

    def check_admin
      if cannot? :manage, Code
        flash[:alert] = "Access denied!"
        redirect_to '/admin'
      end
    end
  end
于 2012-08-10T21:28:51.380 回答