gpt4 book ai didi

ruby-on-rails - 如何对所有请求实现重定向(在特定条件下)?

转载 作者:数据小太阳 更新时间:2023-10-29 07:24:24 26 4
gpt4 key购买 nike

我想设置一些东西,以便如果我的应用程序中的帐户被禁用,我希望所有请求都重定向到“已禁用”消息。

我已经在我的 ApplicationController 中进行了设置:

class ApplicationController < ActionController::Base
before_filter :check_account

def check_account
redirect_to :controller => "main", :action => "disabled" and return if !$account.active?
end
end

当然,这不太有效,因为如果帐户未激活,它会进入无限循环。我希望使用类似的东西:

redirect_to :controller => "main", :action => "disabled" and return if !$account.active? && @controller.controller_name != "main" && @controller.action_name != "disabled"

但我注意到在 Rails v2.1(我正在使用的)中,@controller 现在是 Controller ,这在 ApplicationController 中似乎不起作用。

实现这样的东西的最佳方法是什么?

最佳答案

您有多种选择。

如果您的操作方法“禁用”在应用程序范围内具有唯一名称,您可以向 before_filter 调用添加一个异常,如下所示:

before_filter :check_account, :except => :disabled

如果你想专门检查过滤器中的 Controller 和 Action ,你应该注意这段代码已经是 Controller 对象的一部分。您可以将其称为“ self ”,如下所示:

  def check_account
return if self.controller_name == "main" && self.action_name == "disabled"

redirect_to :controller => "main", :action => "disabled" and return if !$account.active?
end

最后,如果您愿意,可以从 MainController.rb 中覆盖过滤器方法:

  def check_account
return if action_name == "disabled"
super
end

关于ruby-on-rails - 如何对所有请求实现重定向(在特定条件下)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/89543/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com