【问题标题】:Rails - When redirecting from one format to another the flash is not maintainedRails - 从一种格式重定向到另一种格式时,不维护闪存
【发布时间】:2014-03-31 23:46:53
【问题描述】:

我有一个 Ruby on Rails 3.2 应用程序,其中包含从 CSV 请求重定向到 HTML 请求的操作,但重定向后 flash[:notice] 不可用。

第一个动作如下所示:

def first_action
  respond_to do |format|
    format.html do
      redirect_to other_action_controller_url, notice: "This message will be displayed."
    end 
    format.csv do
      redirect_to other_action_controller_url, notice: "The message will NOT be displayed."
    end
  end
end

因此,如果您请求/controller/first_action.csv,它会重定向到/controller/other_action,但不会出现flash 消息。另一方面,如果您请求/controller/first_action,它会重定向到/controller/other_action,并且flash 消息有效。

那么如何才能从一种格式重定向到另一种格式并成功地将消息传递到flash

【问题讨论】:

  • 能否也包含other_action 代码?
  • 我假设您在布局中有一些代码来显示 Flash 消息?如果是这样,请尝试将 flash 设置为:flash[:notice] = 'Foo
  • 是的,我有代码来显示 flash 消息,我确实尝试先明确设置 flash[:notice]。如果相同的块在 format.html 部分中,并且您在没有 .csv 扩展名的情况下发出请求,则重定向会将 flash 传递到下一个扩展名。似乎在 CSV 格式请求中可能会忽略或丢弃闪存?

标签: ruby-on-rails ruby redirect format


【解决方案1】:

尝试如下添加 flash 消息:

def first_action
  respond_to do |format|
    format.html  
    format.csv do
      flash[:notice] = "The CSV is not available."
      redirect_to other_action_controller_url
    end
  end
end

Flash 消息只会在一个重定向操作中持续存在。之后,它会熄灭。

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 2015-06-12
    • 2016-10-09
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多