2

是否可以设置一个 flash[:notice] 消息,该消息将在 www.example.com 上的控制器中设置,但会在 client.example.com 上读取和呈现?

在这个特定的实例中,www.example.com 和 client.example.com 在同一个 Rails 3.2 应用程序中。

用户通过 www.example.com/signup 进入,填写表格,然后被重定向到新创建的子域 client.example.com。

你可以做类似的事情:

flash[:notice] = "hello world", domain: "*.example.com"
4

3 回答 3

4

您需要确保您的会话可以在所有子域之间共享。打开config/initializers/session_store.rb并添加:domain => :all选项:

Yourapp::Application.config.session_store :cookie_store, key: '_yourapp_session', :domain => :all
于 2012-09-10T21:40:14.087 回答
2

Flash 不支持此功能。如果你想做这样的事情,你需要在域上设置一个 cookie,然后从子域中检索它。

您需要设置 cookie 的域,以便在子域中可以访问。这是一个可以更好地放入环境文件或初始化程序的示例!:

Rails.application.config.session_store :cookie_store, :key => '_my_key', :domain => ".yourdomain.com"
于 2012-09-10T21:39:36.163 回答
1

不需要跨子域共享会话的解决方案是将消息作为请求参数发送

# 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

分步说明:

  1. 第三个代码块中的控制器操作会将我们重定向到'/?notice=Hello+world'.

  2. handle_cross_domain_flash_messages看到通过参数传递了一个 flash 消息,并将导致另一个重定向,并将传递给它的 flash 消息。

  3. 重定向现在将转到'/'浏览器中的干净路径。闪存消息在页面上。

它确实需要额外的重定向,但是嘿,没有使用全局会话。

于 2017-03-02T22:03:17.973 回答