我试图限制对用户编辑页面的访问,以便登录用户只能编辑他/她自己的配置文件。仅供参考,我使用的设计进行用户验证,登录,注册等,这应该是很容易与before_action注销用户后更新(使用设计)
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更新之前手动签署用户,然后重定向到编辑页面,但它不起作用。事实上,这甚至不是问题。当我比较current_user和User.find(params [:id])时,current_user登录!但出于某种原因,有before_action:correct_user在那里注销我!
我一直在墙上撞了我的头在这一个相当长的一段时间。任何人都可以帮忙吗?这是一个Rails 4应用程序,并使用最新版本的设计。
谢谢!
就我个人而言,我会避免整个情况,只是让用户资源在你的路线中是唯一的。避免整个查找情况,并让所有操作都在current_user上进行。 – sevenseacat