我有一个用户模型,我想允许登录用户完全删除他们的帐户。我能够允许管理员用户删除其他用户,但是对于用户删除自己的帐户,它不起作用!我做错了什么?
users_controller.rb
class UsersController < ApplicationController
before_filter :signed_in_user,
only: [:index, :edit, :update, :destroy, :following, :followers]
before_filter :correct_user, only: [:edit, :update, :destroy]
before_filter :admin_user, only: :destroy
def index
@users = User.paginate(page: params[:page])
end
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
end
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
sign_in @user
flash[:success] = "Welcome to the Course Management System!"
redirect_to @user
else
render 'new'
end
end
def edit
end
def update
if @user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in @user
redirect_to @user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_url
end
def following
@title = "Following"
@user = User.find(params[:id])
@users = @user.followed_users.paginate(page: params[:page])
render 'show_follow'
end
def followers
@title = "Followers"
@user = User.find(params[:id])
@users = @user.followers.paginate(page: params[:page])
render 'show_follow'
end
private
def correct_user
@user = User.find(params[:id])
redirect_to(root_url) unless current_user?(@user)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
_user.html.erb
<li>
<%= gravatar_for user, size: 52 %>
<%= link_to user.name, user %>
<% if current_user?(user) %>
| <%= link_to "delete", user, method: :delete %>
<% end %>
<% if current_user.admin? && !current_user?(user) %>
| <%= link_to "delete", user, method: :delete,
data: { confirm: "You sure?" } %>
<% end %>
</li>
现在,当我点击“删除”时,它只是将我重定向到主页而不删除用户。当我是管理员时,我可以删除其他用户没有问题。
答案 0 :(得分:2)
你有before_filter阻止非管理员用户达到销毁行动。
删除行:
before_filter :admin_user, only: :destroy
答案 1 :(得分:1)
查看控制器中的过滤器。
before_filter:admin_user,only :: destroy 我想你正在检查一个usr应该是admin来删除记录。正常使用不是管理员,所以他无法删除他的帐户 检查你的日志,这个过滤器将会执行。
答案 2 :(得分:0)
class UsersController < ApplicationController
before_action :correct_user, only: [:edit, :update, :destroy]
# .
# .
# .
def destroy
@user = User.find(params[:id])
# if current user is deleting his/herself whether or not he/she is admin
if current_user?(@user)
@user.destroy
flash[:success] = 'Your account has been destroyed forever.'
redirect_to root_url
# if current_user is admin and is deleting anybody
elsif current_user.admin?
@user.destroy
flash[:success] = 'User deleted.'
redirect_to users_url
# somebody non admin is trying to delete somebody else
# this is supposed to never happen due to before_action :correct_user
else
flash[:danger] = "You can't delete somebody else's account."
redirect_to root_url
end
end
# .
# .
# .
private
def correct_user
@user = User.find(params[:id])
redirect_to(root_url) unless current_user?(@user) || current_user.admin?
end
end