不需要跨子域共享会话的解决方案是将消息作为请求参数发送
# application_controller.rb
class ApplicationController
  before_action :handle_cross_domain_flash_messages
  def handle_cross_domain_flash_messages
    flash.alert = params[:alert] if params[:alert]
    flash.notice = params[:notice] if params[:notice]
  end
end
现在您可以使用任何带有:alert或:notice参数的路径来设置 Flash 消息:
# example path
'/?alert=Hello+World'
# example controller
class PagesController
  def redirect_with_message
    redirect_to root_path(notice: 'Hello world')
  end
end
但是,这样做会将参数留在浏览器的地址栏中。就个人而言,我不喜欢地址栏中的超长地址。一种从地址栏中删除参数同时仍获得所需闪存消息的方法是重定向。
# application_controller.rb
class ApplicationController
  before_action :handle_cross_domain_flash_messages
  def handle_cross_domain_flash_messages
    return unless params[:alert] || params[:notice]
    redirect_to request.path, alert: params[:alert], notice: params[:notice]
  end
end
分步说明:
第三个代码块中的控制器操作会将我们重定向到'/?notice=Hello+world'.
 
将handle_cross_domain_flash_messages看到通过参数传递了一个 flash 消息,并将导致另一个重定向,并将传递给它的 flash 消息。
 
重定向现在将转到'/'浏览器中的干净路径。闪存消息在页面上。
 
它确实需要额外的重定向,但是嘿,没有使用全局会话。