Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 铁路及;CanCan:如果用户已登录,是否允许他/她查看索引页?_Ruby On Rails_Cancan - Fatal编程技术网

Ruby on rails 铁路及;CanCan:如果用户已登录,是否允许他/她查看索引页?

Ruby on rails 铁路及;CanCan:如果用户已登录,是否允许他/她查看索引页?,ruby-on-rails,cancan,Ruby On Rails,Cancan,我在rails 3应用程序上使用authlogic和cancan,我想允许所有登录用户访问用户索引页面,我尝试过类似的方法,但似乎没有效果: 能力等级: class Ability include CanCan::Ability def initialize(user) user ||= User.new can :index, User if UserSession.find can :read, User if UserSession.find en

我在rails 3应用程序上使用authlogic和cancan,我想允许所有登录用户访问
用户索引
页面,我尝试过类似的方法,但似乎没有效果:

能力等级:

class Ability
  include CanCan::Ability

  def initialize(user)

    user ||= User.new

    can :index, User if UserSession.find

    can :read, User if UserSession.find

end
控制器:

def index
    @users = User.search(params[:search]).order('username').page(params[:page]).per(1)
    authorize! :index, @users
  end




def show
     @user = User.find(params[:id])
     authorize! :read, @user
     respond_to do |format|
     format.html # show.html.erb
     format.xml  { render :xml => @user }
    end
  end

谢谢

我发现在我的控制器顶部使用
加载和授权资源
更容易。然后,您的能力类包含所有能力逻辑,而不是散布在控制器上

能力.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    if user
      can :index, User
      can [:show, :edit, :update, :destroy], User, :id => user.id
    end
  end
end
用户\u controller.rb

class UsersController < ApplicationController
  load_and_authorize_resource

  def index
    @users = User.search(params[:search]).order('username').page(params[:page]).per(1)
  end

  def show
  end

  ...

end
class UsersController

我已经有一段时间没有使用authlogic了,因为我现在倾向于使用Desive,所以我不确定我的示例代码是否已准备好authlogic。如果您不想使用
load\u和
,我的代码将显示如何限制用户在能力类中可以看到的内容,但在您的代码中,我会将
:read
更改为
:show

继续我的评论,问题出在以下代码中

authorize! :index, @users

在这里,您将用户数组传递给CanCan的方法,而您的
can:index,User
声明定义了用户对象的授权。

我有CanCan的经验,但我没有使用authlogic。
UserSession.find
的具体功能是什么?检查是否存在用户会话,这是另一位开发人员向我推荐的,并且适用于其他功能,例如:
can:read,user if UserSession.find
但dosent似乎正在使用索引。您可以粘贴控制器操作代码和能力类吗,在哪里工作?试着让它
authorize!:索引,用户
。这很有效,谢谢!你应该把它作为一个答案,这样我就可以投票了!你也能解释一下发生了什么,为什么它不起作用吗?感谢
可以[:显示,:编辑,:更新,:销毁]
可以替换为
:管理
@kishie实际上不是,
:管理
意味着用户可以对给定对象执行任何操作(包括自定义定义的操作)。因此,如果您对用户有一个
投票
操作,
:manage
将允许用户投票,而
[:show,:edit,:update,:destroy]
将不允许用户投票。