如何让CanCan只允许用户在Rails中查看自己的个人资料?

时间:2013-09-11 11:29:06

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 ruby-on-rails-4 cancan

ability.rb我有以下陈述:

if user.is_employee?
  can :schedule, Employee, id: user.employee.id
end

这应该允许员工在/employees/273/schedule查看自己的日程安排。如果员工的身份证是273,该URL将起作用。这有效......员工可以查看该URL。问题是员工也可以查看 所有 其他ID。上述限制员工是否应该只安排自己的id?

更新 :这是我的EmployeeController

class EmployeeController < ApplicationController
  before_filter :authenticate_user!
  authorize_resource
  def schedule
    @employee = Employee.find(params[:id])
  end
end

1 个答案:

答案 0 :(得分:1)

从控制器中删除authorize_resource并在authorize! :schedule, @employee

之后添加@employee = Employee.find(params[:id])

你的控制器

class EmployeeController < ApplicationController
  before_filter :authenticate_user!

  def schedule
   @employee = Employee.find(params[:id])
   authorize! :schedule, @employee
  end
end

然后在你的能力.rb ......

if user.is_employee?
 can :schedule, Employee do |emp|
   user.employee.id == emp.id
 end
end