Rails flash消息未显示在redirect_to中



在一个控制器中,我有

flash[:error] = "Message"
redirect_to :root

:根由另一个控制器处理,视图具有

<% if flash[:error] %>
  <p><%= flash[:error] %></p>
<% end %>

但什么也没有显示出来。我插入<%=调试控制器会话%>,这是我得到的

"flash"=>#<ActionDispatch::Flash::FlashHash:0x2e79208 @used=#<Set: {}>, @closed=false, @flashes={}, @now=nil>}

我做错了什么?

我知道这很晚了,但我在Rails4中遇到了同样的问题。如果您在redirect_to中使用_url帮助程序,则会显示闪烁消息:

def update_post
    respond_to do |format|
        if @post.update(post_params)
            format.html { redirect_to show_post_meta_url, notice: 'Post was successfully updated.' }
        else
            format.html { render action: 'edit_post' }
        end
    end
end

希望这能帮助到别人。

更新(2019):根据评论,这个答案可能不是最新的

检查这个问题:Rails:redirect_to with:error,但flash[:error]为空。

正如Rails API中所述:notice和:alert默认情况下是应用为flash散列值。如果需要设置:error值,则可以这样做:

redirect_to show_path, :flash => { :error => "Insufficient rights!" }

这就是我在控制器中显示警报和通知的方式

redirect_to user_attachments_path, notice: "The file #{@attachment.name} has been uploaded."

当您在当前页面上呈现而不是像这里那样重定向时,请使用flash[:error]flash[:notice]

if params[:attachment].nil?
      flash.now[:alert] = "No file found!"
      render "new"
else

最新更新