我在我的应用程序中使用 CanCan 进行授权。我目前将所有每个用户的信息都存储在 /users/2 或 users/3 或 /users/4 等等。
我的问题是,当用户登录时,他们可以修改 URL 并查看其他用户的敏感内容。如何使用 CanCan 来防止用户(比如 users/2)看到 (users/3) ?
当我将“load_and_authorize_resource”添加到我的用户控制器时,我收到以下错误:
NoMethodError in UsersController#show
undefined method `user_id' for #<User:0x007fee61e90b90>
楷模
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.has_role? :admin
can :manage, :all
can :access, :rails_admin
can :dashboard
else
can :manage, User, :user_id => user.id
end
控制器
class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_path, :alert => exception.message
end
class UsersController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource
def show
@user = User.find(params[:id])
@date = params[:month] ? Date.parse("#{params[:month]}-01") : Date.today
@occasions = @user.occasions.page(params[:page]).per(5)
end