【问题标题】:Rails: How to avoid this redirect loop?Rails:如何避免这种重定向循环?
【发布时间】:2011-08-14 20:57:45
【问题描述】:

我想强制用户在登录时更改密码(假设他们已将某个布尔标记设置为 true)。

现在我正在尝试通过一个名为 change_password_checkbefore_filter 来实现它,它位于 ApplicationController 中。

def change_password_check
  if current_user.change_password == true
    flash[:notice] = "You must be update your password before continuing"
    redirect_to change_password_path
    return false
  end
end

问题显然是我得到了一个重定向循环。

那么,如果用户不在change_password_check 路线上(或发布到user#update),我怎么能只在before_filter 上执行此操作?

我正在运行 Rails 3。

【问题讨论】:

    标签: ruby-on-rails redirect routes


    【解决方案1】:
    before_filter :change_password_check, :except => :change_password
    

    您可以将 only 和 except 指定为 before_filter 的选项。这些接受一组参数,在上述情况下,您只有一个要跳过的方法,但是如果您有另一个要跳过的方法(您的更新操作),您可以这样做:

    before_filter :change_password_check, :except => [:change_password, :update]
    

    only 是 except 的反义词,所以:

    before_filter :change_password_check, :only => :check_me
    

    只有在方法是 check_me 时才会运行。

    【讨论】:

    • 不知道为什么我在想exceptonlyApplicationController 中不起作用……似乎他们确实如此。 :) 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多