【问题标题】:Rails alias_method to current_user for two user models (Devise, CanCan)Rails alias_method 到 current_user 用于两个用户模型(设计,CanCan)
【发布时间】:2014-04-30 17:44:16
【问题描述】:

我正在将 Devise 与两种用户类型一起使用,即 Employer 和 Candidate,它们彼此有很大不同。目前没有 STI,并且每个模型都有一个模型 + 设计认证。在实现 CanCan 进行授权时,我发现需要 current_candidate 或 current_employer 到 current_user 的别名。看来 current_user 只能使用一个别名,因此无法授权非别名用户类型进行任何操作。

class ApplicationController < ActionController::Base
  alias_method :current_user, :current_candidate
  #alias_method :current_user, :current_employer
  #^ can't use both simultaneously!
end

由于只有 current_candidate 可以别名为用于 CanCan 的 current_ability 方法的 current_user,因此上述操作会导致雇主操作的授权失败。

def current_ability
  @current_ability ||= ::Ability.new(current_user)
end

有没有办法有效地将两种用户类型别名为 CanCan 的 current_user?或者是否有某种类型的 before 方法可以在没有别名的情况下设置 current_user?如果需要,很高兴添加更多代码。

【问题讨论】:

    标签: ruby-on-rails-4 devise cancan


    【解决方案1】:

    您可以自己定义current_user 方法。例如,它可以进入ApplicationController

    def current_user
      if current_candidate    # You could use candidate_signed_in? instead.
        current_candidate
      else
        current_employer
      end
    end
    

    那么它应该在你的所有控制器中都可用,并且将被 CanCan 的 current_ability 方法使用。如果您也希望它在视图中可用,一种选择是将helper_method :current_user 行添加到ApplicationController

    另一种选择是覆盖 CanCan current_ability 方法,通过将其添加到您的 ApplicationController 中来获得与上述代码相同的效果:

    def current_ability
      @current_ability ||= ::Ability.new((candidate_signed_in?) ? currrent_candidate : current_employer)
    end
    

    【讨论】:

    • 第一个选项似乎有效,尽管我添加了一个 elsif 条件来检查 current_employer.当访问者没有登录/注册时,有没有办法初始化非模型用户类型?
    • 我想我通过将 current_candidate 设置为 Candidate.new 而不保存它来解决非模型用户的情况。
    • 啊,我不知道你想让它在没有人登录的情况下返回一个非零值。在这种情况下,是的,current_employer 的一个 elsif 和一个新对象未登录的情况下可以解决问题。我猜一个新的Candidate 对象不会给用户你不希望他们拥有的能力?!否则,您可以使用其他一些代表来宾或其他东西的类,或者像我的回答一样让它返回 nil 并在您的控制器/视图中处理这种情况(current_user == nil)。您还可以定义一个检查候选人/雇主签名的user_signed_in? 方法?方法。
    • 候选人的能力是根据他们的 id 来限制的,因此将访客用户设置为候选人对象是没有风险的。好主意。
    • 请注意,这个新的current_user 将无法在您的视图中访问,您需要将其声明为helper_method - stackoverflow.com/a/18659606/1533054
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多