在我的控制器中,我有以下代码:
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开始,它现在的处理方式不同了。 (请参阅here和here)
this question中提供了对此的解决方案。但是,它只能通过将html_safe
调用移动到视图来实现,具有取消所有闪存消息的效果。
我宁愿比这更偏执,有没有办法在控制器的flash消息中包含链接?
答案 0 :(得分:17)
这是解决此问题的一种可能方法。在您的ApplicationController
中添加一个前置过滤器,只有在flash[:notice]
设置后才能使flash[:html_safe]
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