来自Rails 4中控制器的html_safe的Flash消息(安全版)

011*_*112 12 ruby ruby-on-rails ruby-on-rails-4

在我的控制器中,我有以下代码:

    format.html { redirect_to new_customer_url,
                notice: %Q[ A customer already exists with with this shopping id. Edit this customer #{view_context.link_to("here", edit_customer_url(@duplicate))}.
    ].html_safe
Run Code Online (Sandbox Code Playgroud)

我希望能够在flash消息中包含一个链接,所以(正如你所看到的)我将html_safe称为unescape字符串.但是,从Rails 4.1开始,它现在的处理方式不同了.(见这里这里)

这个问题中已经提供了解决方案.但是,它只能通过将html_safe调用移动到视图来实现,具有取消所有闪存消息的效果.

我宁愿比这更偏执,有没有办法在控制器的flash消息中包含链接?

Wiz*_*Ogz 17

这是解决此问题的一种可能方法.添加一个前置过滤器,只有设置后才ApplicationController能使flash[:notice]html安全flash[:html_safe].然后你可以控制什么时候和什么时候不要完全从控制器发出通知html安全.

before_filter -> { flash.now[:notice] = flash[:notice].html_safe if flash[:html_safe] && flash[:notice] }
Run Code Online (Sandbox Code Playgroud)

然后您的示例可以修改为:

format.html do
  redirect_to(
    new_customer_url,
    notice: %Q[ A customer already exists with with this shopping id. Edit this customer #{view_context.link_to("here", edit_customer_url(@duplicate))}.],
    flash: { html_safe: true }
  )
end
Run Code Online (Sandbox Code Playgroud)

  • 奇迹般有效!谢谢.=) (2认同)
  • 在一个请求结束时,@ sixty4bit会将闪存中的数据序列化到数据存储(cookie,数据库,redis,memcached等)。然后在下一个请求开始时反序列化。在序列化和反序列化的过程中,不会保留html_safe信息(尽管可以实现该信息)。 (2认同)