2013-11-27 22 views
0

我试图限制对用户编辑页面的访问,以便登录用户只能编辑他/她自己的配置文件。仅供参考,我使用的设计进行用户验证,登录,注册等,这应该是很容易与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应用程序,并使用最新版本的设计。

谢谢!

+0

就我个人而言,我会避免整个情况,只是让用户资源在你的路线中是唯一的。避免整个查找情况,并让所有操作都在current_user上进行。 – sevenseacat

回答

0

我不确定你真的需要这里的find_user方法。

class UsersController < ApplicationController 
    respond_to :html 

    def update 
    current_user.update_attributes user_params 
    respond_with current_user, location: [:edit, current_user] 
    end 

    private 
    def user_params 
    ... 
    end 
end 

看到,你只能让用户编辑自己的唱片,你可以在update方法使用current_user。另外,如果您很乐意使用标准的Rails约定来进行CRUD操作,那么respond_to/with通过为您实现这一点,可以节省一点时间和代码。我使用了location选项,否则respond_with默认为资源的show页面。

+0

查找用户是为了消除重复的代码。这不是必要的,但我认为它很好。我试着更新current_user,但它仍然出现:( –

+0

如果您使用'current_user',则不需要执行'before_action:correct_user'。 –