简体   繁体   English

Rails后渲染Flash成功

[英]Rails post-render flash succeed

I'm learning rails right now. 我正在学习rails。 Today for some odd reasons I put the line of flash after the redirect, which is obviously a bad practice. 今天,出于某些奇怪的原因,我将闪存行放在了重定向之后,这显然是一种不好的做法。 But strangely, after the redirect the flash works. 但是奇怪的是,在重定向之后,闪光灯可以工作了。

Isn't flash supposed to be used to carry the message to the next request? 难道不应该使用Flash将消息传送到下一个请求吗?

Bearing this in mind I added a line that is supposed to makes the program stop for 10 seconds after the redirect. 考虑到这一点,我添加了一行,该行应该使程序在重定向后停止10秒钟。 Then I noticed that the entire website will hold for 10 seconds before redirect. 然后,我注意到整个网站将在重定向前保持10秒钟。 Why did redirect_to method wait 10 seconds? 为什么redirect_to方法要等待10秒? This will not be the case if I replace the redirect_to method with render. 如果我用render替换redirect_to方法,情况就不会如此。 I've put the code blocks below. 我将代码块放在下面。

redirect_to root_url
message = "Account not activated. "
message += "Check your email for the activation link."
flash[:danger] = message #can still see the flash after redirect

Entire Controller: 整个控制器:

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      if user.activated?
        log_in user
        params[:session][:remember_me] == '1' ? remember(user) : forget(user)
        redirect_back_or user 
      else 
        redirect_to root_url
        sleep 10
        message = "Account not activated. "
        message += "Check your email for the activation link."
        flash[:danger] = message       
      end
    else
      flash.now[:danger] = "Invalid email/password combination"
      render "new"
    end
  end

  def destroy
    log_out if logged_in?
    redirect_to root_url
  end
end

Before Rails does anything with your controller method it reads and builds the response. 在Rails用控制器方法做任何事情之前,它会读取并构建响应。

If you were to return immediately after calling redirect_to your flash wouldn't be captured and inserted into the appropriate methods. 如果您在调用redirect_to之后立即返回,则不会捕获您的Flash并将其插入适当的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM