【问题标题】:How to get CanCan to only allow user to view their own profile in Rails?如何让 CanCan 只允许用户在 Rails 中查看自己的个人资料?
【发布时间】:2013-09-11 11:29:06
【问题描述】:

ability.rb我有以下声明:

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

这应该允许员工在/employees/273/schedule 查看自己的日程安排。如果员工的 ID 为 273,则该 URL 将起作用。这有效……员工能够查看该 URL。问题是员工也可以查看 所有 其他 ID。以上不应该限制员工只能安排自己的id吗?

更新:这是我的EmployeeController

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

【问题讨论】:

  • 请出示您的控制器
  • @apneadiving - 我在问题中发布了控制器
  • 要查看资源需要加载和授权
  • 我确实有authorize_resource,我以为load_and_authorize 只是做了额外的加载资源的步骤。
  • authorize 需要该资源,因此您可以预先添加一个前置过滤器来自己进行操作,或者使用 load_and_authorize

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


【解决方案1】:

从控制器中删除authorize_resource并在@employee = Employee.find(params[:id])之后添加authorize! :schedule, @employee

你的控制器

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多