before_action注销用户发布更新(使用设计)

时间:2013-11-27 06:43:58

标签: ruby-on-rails devise

我正在尝试限制对用户编辑页面的访问,以便登录用户只能编辑他/她自己的个人资料。仅供参考,我正在使用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应用程序,我正在使用最新版本的设计。

谢谢!

1 个答案:

答案 0 :(得分: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

看到您只让用户编辑自己的记录,您只需在current_user方法中使用update

此外,如果您乐意使用标准Rails约定进行CRUD操作,那么respond_to/with将为您节省一些时间和代码。我使用location选项,否则respond_with默认使用资源的show页面。