在我的控制器中,我有以下代码:
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[:notice]
html安全只有 flash[:html_safe]
已设定。然后你可以控制什么时候和什么时候不要让通知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
这是解决此问题的一种可能方法。添加一个前过滤器到您的 ApplicationController
这将使 flash[:notice]
html安全只有 flash[:html_safe]
已设定。然后你可以控制什么时候和什么时候不要让通知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