0

请帮助解决问题。我尝试在安装“cancan”和“cancancan”gem 后设置权限。

架构.rb:

create_table "roles", force: :cascade do |t|
  t.string   "name"
end

create_table "roles_users", id: false, force: :cascade do |t|
  t.integer "role_id"
  t.integer "user_id"
end

create_table "users", force: :cascade do |t|
  t.string   "email",                  default: "", null: false
  ................................................................
  t.datetime "created_at"
  t.datetime "updated_at"
end

楷模:

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles

  def role?(role)
    return !!self.roles.find_by_name(role.to_s.camelize)
  end     
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

应用程序/模型/ability.rb:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)

    if user.role? :admin
      can :manage, :all
    elsif user.role? :manager
      can :manage, :review
      cannot :manage, :user
    elsif user.role? :user
      cannot :manage, :all
    end   
  end
end

我填写了我的角色表以下值:

id    name  
0     user
1     manager
2     admin

我填写了我的联接表“roles_users”以下值:

role_id       user_id
2             2
1             3
0             1

但运行应用程序权限后没有效果。问题是管理员可以更改所有用户的信息。这是不对的。请帮助修复它

ps:

my user controller:
class UserController < ApplicationController
  load_and_authorize_resource
end

经理通过管理面板更改用户信息后,控制台输出如下:

Started GET "/admin/users/1" for 127.0.0.1 at 2015-09-19 20:53:47 +0300
Processing by Admin::UsersController#show as HTML
  Parameters: {"id"=>"1"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 3]]
   (0.1ms)  SELECT COUNT(*) FROM "active_admin_comments" WHERE "active_admin_comments"."resource_type" = ? AND "active_admin_comments"."resource_id" = ? AND "active_admin_comments"."namespace" = ?  [["resource_type", "User"], ["resource_id", "1"], ["namespace", "admin"]]
  CACHE (0.0ms)  SELECT COUNT(*) FROM "active_admin_comments" WHERE "active_admin_comments"."resource_type" = ? AND "active_admin_comments"."resource_id" = ? AND "active_admin_comments"."namespace" = ?  [["resource_type", "User"], ["resource_id", "1"], ["namespace", "admin"]]
  Rendered /home/kalinin/.rvm/gems/ruby-2.0.0-p598/bundler/gems/activeadmin-893b46c6530c/app/views/active_admin/resource/show.html.arb (316.7ms)
Completed 200 OK in 321ms (Views: 318.9ms | ActiveRecord: 0.3ms)
4

1 回答 1

1

您的方法中不需要该.camelize调用role?,因为您在 db 中的所有角色都存储在小写 ( manager) 中,而不是 camelCase ( ManagerOfTheApplication) 中。

看来您Admin::UsersController位于active_admin. 尝试启用active_admincan_can集成

config.authorization_adapter = ActiveAdmin::CanCanAdapter

查看上面的链接了解详细信息。

于 2015-09-19T17:35:54.957 回答