如何覆盖CanCanCan中的默认方法

How to override the default method in CanCanCan

CanCanCan 对应用程序做出两个假设:

1*定义权限的能力class。

2*控制器中的一个 current_user 方法,returns 当前用户模型。

在我的例子中,我有两个模型对象和主题(我可以创建、更新、销毁)它们都使用 CRUD 操作。

现在我想使用 CanCanCan 库授权来限制对此对象的访问。我知道 CanCanCan 期望控制器中存在 current_user 方法并设置一些身份验证(如 Devise)。我如何覆盖需要 current_user 的默认方法并将其传递给 current_subject,因为该方法应该可以访问对象。

使用新辅助方法的别名:

只需将控制器中的 current_user 辅助方法别名为您正在使用的实际辅助方法:

class ApplicationController < ActionController::Base
  alias_method :current_user, :current_subject # or whatever your helper method is called - this is untested btw
end

# Source: https://github.com/CanCanCommunity/cancancan/wiki/changing-defaults