The plan is for my users to be able to only see other users in users#index if those users belong to the same studio (user.studio_id).
It almost works perfectly. The only hiccup is… the first time any user (including admin) goes to users/index, they get an unauthorized message. If they try again, they get the index with only the appropriate records appearing. How can I make it stop choking on the authorization the first time they go there?
ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
can :read, User
if user.role? :Student
...
cannot :read, User, ["studio_id <> ?", user.studio_id] do |u|
u.studio_id != user.studio_id
end
can :update, User, ["id = ?", user.id] do |u|
u.id == user.id
end
end
if user.role? :Teacher
...
can :update, User, ["id = ?", user.id] do |u|
u.id == user.id
end
end
if user.role? :Director
...
can :manage, User, ["studio_id = ?", user.studio_id] do |u|
u.studio_id == user.studio_id
end
can :create, User
end
cannot :delete, [Studio, Event]
cannot :change_studio, [User]
if user.role? :Admin
can :manage, :all
can :see_ids, :all
can :change_studio, User
end
end
end
end
UsersController
class UsersController < ApplicationController
respond_to :html, :xml, :json
load_and_authorize_resource #:only => [:show,:new,:destroy,:edit,:update]
def index
end
...
end
Maybe you can try it the other way around and remove initial
can :read, Userand then allow bycan :read, User, :studio_id => user.studio_id