【问题标题】:Rails flash message not showing in redirect_toRails flash 消息未显示在 redirect_to 中
【发布时间】:2012-04-01 12:30:32
【问题描述】:

在一个控制器中我有

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

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

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

但没有显示任何内容。我插入了 ,这就是我得到的

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

我做错了什么?

【问题讨论】:

  • 你的路由文件和 root 的控制器动作是什么样的?我试图复制这个,但它对我有用,所以也许这些会有助于解决这个问题。
  • 杰夫,感谢您指出路线问题。事实证明,我的伙伴为 root_handler 设置了另一个重定向。在第二次重定向之前添加 flash.keep 后,出现错误。
  • 刚刚在post action中遇到了同样的问题,kimkunji你解决了吗?
  • 见我上面的评论。事实证明,我的伙伴为 root_handler 设置了另一个重定向。在第二次重定向之前添加 flash.keep 后,出现错误。

标签: ruby-on-rails


【解决方案1】:

我知道这已经很晚了,但我在 Rails 4 中遇到了同样的问题。如果您在 redirect_to 中使用 _url 帮助程序,则会通过 Flash 消息:

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

希望这对某人有所帮助。

【讨论】:

    【解决方案2】:

    更新(2019 年):根据 cmets,此答案可能不是最新的。

    检查这个问题:Rails: redirect_to with :error, but flash[:error] empty

    如 Rails API 中所述,默认情况下只有 :notice 和 :alert 作为闪存哈希值应用。如果你需要设置 :error 值,你 可以这样做:

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

    【讨论】:

    • 我试过你的代码。即使我从 :error 切换到 :alert 后仍然无法工作。
    • 确认确认,这不起作用。
    【解决方案3】:

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

    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
    

    【讨论】:

    • render 'new' 不起作用,因为它丢失了对 record.new 和 redirect_to some_url(@record) 的引用,注意:“message”丢失了 flash 提供的格式
    • @LuisFlores 不正确。 Rails API 允许直接为通知和警报类型传递 Flash 消息。对于其他类型的消息,您需要以redirect_to url flash: {other_type: message} 格式指定消息。对于所有其他情况,此解决方案有效。参考 - guides.rubyonrails.org/…
    猜你喜欢
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    相关资源
    最近更新 更多