我在我的应用程序中使用 CanCan 进行授权。我目前将所有每个用户的信息存储在/users/2 或 users/3 或/users/4 等处。
我的问题是,当用户登录时,他们只需修改 URL 即可查看其他用户的敏感内容。如何使用 CanCan 阻止用户(例如 users/2)看到(users/3)?
当我将“load_and_authorize_resource”添加到我的用户 Controller 时,出现以下错误:
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
Controller
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
最佳答案
您是否尝试过将 load_and_authorize_resource
放在 UsersController
的顶部?
关于ruby-on-rails - CanCan 的用户授权 : NoMethodError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11298134/