【发布时间】:2013-12-12 16:37:49
【问题描述】:
我正在尝试限制对用户编辑页面的访问,以便登录用户只能编辑他/她自己的个人资料。仅供参考,我正在使用 Devise 进行用户身份验证、登录、注册等。这应该很容易做到
class UsersController < ApplicationController
before_action :find_user, only: [:edit, :update]
before_action :correct_user, only: [:edit, :update]
def edit
end
def update
if @user.update_attributes(user_params)
flash[:success] = 'Profile Updated!'
redirect_to edit_user_path(@user)
else
render 'edit'
end
end
private
def user_params
# code left out... but pretty self explanatory right?
end
def find_user
@user = User.find(params[:id])
end
def correct_user
redirect_to(root_url) unless current_user == find_user
end
end
奇怪的是,当我有 before_action :correct_user 时,当用户更新时……它会在更新后将用户注销!当我没有 before_action :correct_user 时,它会让用户保持登录状态并重定向到用户的编辑页面。在重定向到编辑页面之前,我尝试在 def update 中手动为用户签名,但它不起作用。事实上,这甚至都不是问题。当我比较 current_user 和 User.find(params[:id]) 时,current_user 已登录!但由于某种原因,有 before_action :correct_user 让我退出!
在这个问题上,我已经把头撞在墙上很长一段时间了。任何人都可以帮忙吗?这是一个 Rails 4 应用程序,正在使用最新版本的设计。
谢谢!
【问题讨论】:
-
就个人而言,我会避免整个情况,只是让用户资源在你的路线中成为一个单一的资源。避免整个查找情况,只对 current_user 执行所有操作。
标签: ruby-on-rails devise