【问题标题】:CanCan does not get userCanCan 无法获取用户
【发布时间】:2014-05-05 01:43:33
【问题描述】:

我在使用 cancan 时遇到了一些问题,我不知道我做错了什么。

在我的 /rails_admin.rb 中

config.authorize_with :cancan

在我的模型/ability.rb 中

class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
      user ||= User.new # guest user (not logged in)
      if user.admin?
        can :manage, :all
      else
        can :read, :all
      end
end

我有管理员吗?给出真或假值并对其进行测试的方法。

问题是我的能力类没有用用户初始化。如果我将 binding.pry 放在 def initialize(user) 下,我会得到 nil win 我打电话给 user。我错过了什么?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您在哪里调用授权! 'current_user' 字段/方法是否存在或者也没有?

    CanCan 期望您定义了“current_user”方法。

    许多用于身份验证的流行 gem,例如 Devise,都会自动为您提供。

    如果您编写了自己的登录脚本,则需要提供一个名为“current_user”的帮助程序或控制器方法,该方法返回当前登录的用户。

    编辑:参考有关 CanCan 期望的更多详细信息

    GitHub: cancan: Changing Defaults

    【讨论】:

    • 我正在使用设计,但 current_user 在此类中也为零。我可以在网站本身上调用 current_user 并且它可以工作。我想我不知道在哪里打电话给授权!我只想授权这个管理页面。该网站的其余部分是公平的游戏。
    • 我刚看到你的链接。这就是我想找的东西!谢谢!
    猜你喜欢
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 2016-10-28
    相关资源
    最近更新 更多