In my controller I have the following code:
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
I would like to be able to include a link in a flash message, so (as you can see) I call html_safe to unescape the string. However, it seems that as of Rails 4.1 this is now handled differently. (See here and here)
A solution to this has been provided in this question. However, it only does so by moving the html_safe
call to the view, having the effect of unescaping all flash messages.
I would prefer to be a bit more paranoid than that, is there any way to include the link in the flash message from the controller?
Here is one possible way to solve this problem. Add a before filter to your ApplicationController
which will make flash[:notice]
html safe only if flash[:html_safe]
is set. Then you can control when and when not to make notices html safe completely from the controller.
before_filter -> { flash.now[:notice] = flash[:notice].html_safe if flash[:html_safe] && flash[:notice] }
Then your example could be modified to this:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With