我在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
Controller :
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
谢谢
最佳答案
我发现在 Controller 顶部使用 load_and_authorize_resource
更容易。然后你的能力类包含所有的能力逻辑,而不是让它散布在你的 Controller 上。
能力.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
更改为:显示
。
关于ruby-on-rails - Rails 和 CanCan : If user is logged in then allow him/her to view index page?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6153637/