Rails CanCan Simple_form关联问题

时间:2012-06-05 13:48:25

标签: ruby-on-rails cancan simple-form

为什么不能阻止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只能创建(管理)他自己部门的用户。

这是日志,显示选择是在部门选择的位置使用而不是在视图中完成。

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问题吗?怎么解决?

0 个答案:

没有答案