我在Rails 4(cancancan)上使用CanCan,我只想授权当前用户访问设置页面。
例如,用户ID 1应该只是access / settings / 1。用户ID 1应该无法查看/ settings / 2或任何其他ID。
我的角色是:admin,user,guest,banned
Ability.rb:
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, :all
else
can :read, :all
end
end
end
用户控制器:
def settings
@user = User.find(params[:id])
end
答案 0 :(得分:2)
来自authorizing controller actions的文档:
# app/controllers/users_controller.rb
def settings
@user = User.find(params[:id])
authorize! :settings, @user
end
这假设您已正确建立了访问参数:
# app/models/ability.rb
can :settings, User do |u|
user.id == u.id
end