Rails & CanCan: If user is logged in then allow him/her to view index page?
I am using authlogic and cancan on a rails 3 application, I want to allow all logged in users to access the users index
page, i have tried something like this but it dosent seem to be working:
ability class:
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开发者_StackOverflow[: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
thanks
I find it's easier to use load_and_authorize_resource
at the top of my controllers. Then your ability class contains all the ability logic instead of having it strewn about your controllers.
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
I haven't used authlogic in a while as I tend to use devise now, so I'm not sure if my sample code is authlogic ready. If you don't want to use load_and_authorize_resource
, my code shows how to limit what users can see in the ability class, but in your code I'd change :read
to :show
.
Continuing from my comment, the problem was in the following code
authorize! :index, @users
Here, you're passing an Array of users to the CanCan's method, while your can :index, User
declaration defines the authorization for a User object.
精彩评论