如何解决Rails&CanCan:如果用户已登录,则允许他/她查看索引页面?
| 我在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
谢谢
解决方法
继续我的评论,问题出在以下代码中
authorize! :index,@users
在这里,您正在将用户数组传递给CanCan \的方法,而您的“ 4”声明则定义了User对象的授权。
, 我发现在控制器顶部使用ѭ5会更容易。然后,您的异能类将包含所有异能逻辑,而不是将其散布在您的控制器上。
能力
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
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。