Ruby on rails 每个用户一个角色CanCan,未定义方法';角色';问题

Ruby on rails 每个用户一个角色CanCan,未定义方法';角色';问题,ruby-on-rails,ruby,authorization,roles,cancan,Ruby On Rails,Ruby,Authorization,Roles,Cancan,真的很困惑。角色已经设置好,并且按照以下步骤很好地工作。我的用户模型如下 class User < ActiveRecord::Base ROLES = %w[admin landlord] def role?(role) roles.include? role.to_s end end class Ability include CanCan::Ability def initialize(user) if user.role

真的很困惑。角色已经设置好,并且按照以下步骤很好地工作。我的用户模型如下

class User < ActiveRecord::Base

    ROLES = %w[admin landlord]

    def role?(role)
     roles.include? role.to_s
    end
 end
class Ability
  include CanCan::Ability

  def initialize(user)
    if user.role == "admin"
      can :manage, :all
    else
     can :read, :all
    end
  end
end
这是我在终点站看到的

NoMethodError (undefined method `role' for #<ActionDispatch::Session::AbstractStore::SessionHash:0x1044d46a8>):
  app/models/ability.rb:5:in `initialize'
  app/controllers/application_controller.rb:6:in `new'
  app/controllers/application_controller.rb:6:in `current_ability'
NoMethodError(未定义的#的“角色”方法):
app/models/ability.rb:5:in'initialize'
app/controllers/application_controllers.rb:6:in'new'
app/controllers/application\u controller.rb:6:在“当前能力”中

正如你所说,我只是在学习!即使是朝着正确的方向轻推也会令人惊讶。谢谢。

问题是您定义了
role?
方法,但在
ability.rb
中,您调用了
role
方法,该方法当然没有定义

正确的方法是

def initialize(user)
  if user.role? "admin"
    can :manage, :all
  else
    can :read, :all
  end
end

问题是您定义了
role?
方法,但在
ability.rb
中,您调用了
role
方法,该方法当然未定义

正确的方法是

def initialize(user)
  if user.role? "admin"
    can :manage, :all
  else
    can :read, :all
  end
end

您正在向CanCan传递一个会话。您需要传递当前已登录的用户。我猜在rails手册的解释中,应该有一种方法可以从变量会话访问该用户。将该用户作为参数传递给该能力

如果用户未登录,我将发送一个新用户

您需要将代码重构为如下内容:

def current_ability
  if session[:user_id]  # Replace with the method to get the user from your session
    user = User.find(session[:user_id])
  else
    user = User.new
  end

  @current_ability ||= Ability.new(user)
end

您正在向CanCan传递一个会话。您需要传递当前已登录的用户。我猜在rails手册的解释中,应该有一种方法可以从变量会话访问该用户。将该用户作为参数传递给该能力

如果用户未登录,我将发送一个新用户

您需要将代码重构为如下内容:

def current_ability
  if session[:user_id]  # Replace with the method to get the user from your session
    user = User.find(session[:user_id])
  else
    user = User.new
  end

  @current_ability ||= Ability.new(user)
end

我猜当前用户的值有问题。你在用Desive吗?您在当前功能中定义了什么?我没有使用Deviate,只是从我拥有的Rails 3书籍中对登录进行了编码。def current_ability@current_ability | |=ability.new(session)end我猜当前_用户的值有问题。你在用Desive吗?您在当前功能中定义了什么?我没有使用Deviate,只是从我拥有的Rails 3书籍中对登录进行了编码。def current_ability@current_ability | |=ability.new(session)endI-see,谢谢你的关注。我编辑了我的代码,想说。def current_ability@current_ability | |=ability.new(session[:user_id])结束,但我现在得到的错误是:未定义方法'role',因为3:FixnumYou正在传递用户的id,而不是用户本身。如果会话[:User_id]存在,您需要找到该用户。(就像我发布的代码中一样)我明白了,谢谢您的发现。我编辑了我的代码,想说。def current_ability@current_ability | |=ability.new(session[:user_id])结束,但我现在得到的错误是:未定义方法'role',因为3:FixnumYou正在传递用户的id,而不是用户本身。如果会话[:User_id]存在,您需要找到该用户