在 Rails 中是否可以检查重定向或渲染是否已经发出? [英] Is it possible in Rails to check whether a redirect or render had already been issued?

查看:38
本文介绍了在 Rails 中是否可以检查重定向或渲染是否已经发出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 2.0.2、Rails 4.0.3、巫术 0.8.5

Ruby 2.0.2, Rails 4.0.3, Sorcery 0.8.5

我尝试在我的代码中发出重定向,但收到错误消息,指出已发出重定向或呈现.如果是这样,我很乐意回来.但是,如果由于任何其他原因调用该方法,我想检查是否已发出重定向或呈现,如果没有,则发出它.该代码是基于 Sorcery 的身份验证.

I tried to issue a redirect in my code, only to receive the error message that a redirect or render had already been issued. If that is the case, I'm happy to return. However, if the method is called for any other reason, I'd like to check to see if a redirect or render had been issued and, if not, issue it. The code is authentication based on Sorcery.

在应用程序控制器中,我有:

In the application controller, I have:

  def not_authenticated
    redirect_to login_url # , :alert => "First log in to view this page."
  end

这最终会检查 current_user,如下所示:

This ends up checking for current_user, as follows:

  def current_user
    @current_user ||= @view.current_user unless @view.blank?
    begin
      @current_user ||= Associate.find(session[:user_id]) unless session[:user_id].blank?
    rescue ActiveRecord::RecordNotFound => e
      return
    end
    current_user = @current_user
  end

在救援中,我想确定重定向或渲染是否已经发生,如果没有,我可以重定向_到 login_url.当然,这意味着它是从不同的方法调用的,它是.谢谢.

In the rescue, I'd like to determine whether or not a redirect or render had already occurred, so that I could redirect_to login_url if not. This would mean, of course, that it was called from a different method, which it is. Thanks.

推荐答案

您可以在控制器中调用 performed? 来检查是 render 还是 redirect_to已被调用:

You can call performed? in your controller to check if render or redirect_to has been called already:

performed?               # => false
redirect_to(login_path)
performed?               # => true 

阅读更多关于已执行? 在 Rails 文档中.

Read more about performed? in the Rails docs.

这篇关于在 Rails 中是否可以检查重定向或渲染是否已经发出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆