【问题标题】:before_action logs out user post update (using devise)before_action 注销用户发布更新(使用设计)
【发布时间】: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


【解决方案1】:

我不确定您是否真的需要 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 页面。

【讨论】:

  • 查找用户是为了消除重复代码。这不是必需的,但我认为这很好。我尝试使用 current_user 进行更新,但它仍然退出 :(
  • 如果您使用的是current_user,则无需执行before_action :correct_user
猜你喜欢
  • 2022-08-16
  • 2016-04-27
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
相关资源
最近更新 更多