1

为什么不能阻止dept_tech 角色在dept_tech 角色无权访问的部门中创建用户?

我使用 cancan 进行自动化,使用 simple_form 进行视图。我有一个用户模型和一个部门模型。

class User < ActiveRecord::Base
  belongs_to :department
  ...
end

class Department < ActiveRecord::Base
  has_many :departments
  ...
end

我也有能力模型

class Ability
  include CanCan::Ability

  def initialize(user)
    Rails.logger.debug {" >>>>>>> user id: #{user.id} ......
    if user.role? :admin
     ...
    elseif user.role? :dept_tech
      Rails.logger.debug {" >>>>>>> role 6 ......
      can :manage, User, :department_id => user.department_id
      can :read, Department, :id => user.department_id
      Rails.logger.debug {" >>>>>>> user.department: #{user.department_id}}
    end
  end
 end

和用户控制器:

load_and_authorize_resource
...
def new

  respond_to do |format|
    Rails.logger.debug {" >>>> here"}
    format.html # new.html.erb
  end
  Rails.logger.debug {" >>>> there"}
end
...

还有一个

load_and_authorize_resource

在部门控制器。

和一个使用 simple_form 的 _form 视图助手

<% simple_form_for @user, :html => {class => 'form-horizontal' } do |f| %>
  <%= f.input :email %>
  Rails.logger.debug {" >>>> view"}
  <%= f.association :department %>
  ....
<% end %>

这很好用,dept_tech 只能为部门做索引和显示操作。它也适用于索引,为用户显示操作。但是,当对用户执行新操作时,部门的 collection_select 会显示所有部门,而不仅仅是 dept_tech 的部门。

想法是 dept_tech 只能创建(管理)他自己部门的用户。

这是日志,显示在没有选择部门的位置时使用了 select,并且在视图中完成。

Started GET "/users/new" for 127.0.0.1 at 2012-06-05 13:57:58 +0200
[2012-06-05 13:57:58 +0200] Processing by UsersController#new as HTML
[2012-06-05 13:57:58 +0200]   User Load (0.9ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 2]]
[2012-06-05 13:57:58 +0200]  >>>> User id: 2, User role: ["dept_tech"], roles_mask: 64
[2012-06-05 13:57:58 +0200]  >>>> Role 6
[2012-06-05 13:57:58 +0200]  >>>> user.department: 2
[2012-06-05 13:57:58 +0200]  >>>> here
[2012-06-05 13:57:58 +0200]  >>>> view
[2012-06-05 13:57:58 +0200]   Department Load (0.9ms)  SELECT "departments".* FROM "departments" 
[2012-06-05 13:57:58 +0200]   Rendered users/_form.html.erb (45.7ms)
[2012-06-05 13:57:58 +0200]   Rendered users/new.html.erb within layouts/application (46.5ms)
[2012-06-05 13:57:58 +0200]  >>>> there
[2012-06-05 13:57:58 +0200] Completed 200 OK in 63ms (Views: 56.4ms | ActiveRecord: 1.8ms)

日志显示在视图中调用 SQL 也就不足为奇了。这是一个 simple_form 问题吗?怎么解决?

4

0 回答 0