我正在使用CanCan和Devise,但设计用户是通过自定义UsersController管理的。我只想让一个logged_in用户看到编辑和销毁链接。但是现在依赖于传递给能力等级的内容,它要么为所有用户(包括logged_in用户)隐藏编辑和销毁链接,要么暴露编辑< / strong>和销毁所有用户的链接任何signed_in用户,因此他们可以编辑任何用户帐户事件,如果不是他们的。
用户/ index.html.erb
<% @users.each do |user| %>
<div class="col-lg-3 col-sm-4 col-6">
<div><%= user.email %></div>
<% if user_signed_in? %>
<% if can? :update, user %>
<div class=" btn "><%= link_to "Edit", edit_user_path(user) %> </div>
<% end %>
<% if can? :destroy, user %>
<div class="btn btn-danger"><%= link_to 'Remove', user, method: :delete, data: {confirmation: 'Are you sure'} %></div>
<% end %>
<div><%= link_to "Sign Out", destroy_user_session_path, method: :delete %> </div>
<% end %> <!-- closes user_signed_in? -->
</div>
<% end %>
能力等级
class Ability
include CanCan::Ability
def initialize(user)
#to ensure user object is not nil when no user object is passed in
user ||= User.new
can :manage, User do |user|
#this exposes the destroy and edit links for all users including users not yet signed_in
#user.id == user.id
#this hide the destroy and edit links for all users including signed_in user
user == :user_id
end
end
end
请注意,我在第二个屏幕截图
下添加了Userscontroller屏幕截图1显示,如果能力等级中的 user.id == user.id 取消注释,则会公开 destroy ,所有用户编辑链接尚未签名, signed_in 用户可以编辑不属于帐户。在屏幕截图中,真实的signed_in用户的电子邮件是 a@test.com ,但您可以看到他有权访问编辑和销毁链接对于未签名的用户 b@test.com
屏幕截图2是我们在能力等级中取消注释 user ==:user_id 时获得的内容。即使是signed_in用户也可以隐藏编辑和销毁链接。
缩短版本的用户控制器
class UsersController < ApplicationController
before_action :set_user, only: [:show, :update, :destroy]
before_filter :authenticate_user!, except: [:new, :create]
load_and_authorize_resource , only: [:index, :edit, :destroy]
respond_to :html, :json
def index
@users = User.all
respond_with @users
end
def edit
#@user = User.find(params[:id])
#respond_with @user
end
def destroy
@user.destroy
redirect_to users_path, {notice: 'A user was removed'}
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
会话控制器
class UsersSessionsController < Devise::SessionsController
respond_to :html, :json
def create
super
if signed_in?(resource)
#call the code to transfer guest cart to signed_in user
load_current_cart
end
end
end
由@ gotva的答案修正如下。所以:**可以:管理,用户,:id =&gt; user.id 仅 a@test.com ,login_in用户会看到编辑和销毁链接。新截图:
答案 0 :(得分:1)
尝试通过哈希定义能力(不是阻止) https://github.com/ryanb/cancan/wiki/Defining-Abilities#hash-of-conditions
can :manage, User, :id => user.id
答案 1 :(得分:0)
在你的能力中.rb:你是否尝试过:
user ||= User.new # guest user
# you can here try some condition if you have multi user types
can [:new, :create], :all