我在rails 3应用程序上使用authlogic和cancan,我想允许所有登录用户访问users index
页面,我尝试了类似这样的东西,但它似乎正在工作:
能力等级:
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
谢谢
答案 0 :(得分:4)
我发现在我的控制器顶部使用load_and_authorize_resource
更容易。然后你的能力类包含所有的能力逻辑,而不是让它散落在你的控制器上。
ability.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
users_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
我暂时没有使用authlogic,因为我现在倾向于使用devise,所以我不确定我的示例代码是否已准备好authlogic。如果您不想使用load_and_authorize_resource
,我的代码会显示如何限制用户在能力类中看到的内容,但在您的代码中,我会将:read
更改为:show
。< / p>
答案 1 :(得分:1)
继续发表评论,问题出现在以下代码中
authorize! :index, @users
在这里,您将一个用户数组传递给CanCan的方法,而您的can :index, User
声明定义了User对象的授权。