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

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

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 

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

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

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

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

 before_filter -> { flash.now[:notice] = flash[:notice].html_safe if flash[:html_safe] && flash[:notice] } 

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

 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