Search code examples
ruby-on-railslink-toflash-messageviewcontext

I'm trying to implement `link_to` in a flash message for an update action in a controller in Rails but I cannot get it to render to the browser


I have a controller like this in my project:

class BriefcasesController < ApplicationController
  ...

  def update
    @super_power = SuperPower.find(params[:super_power_id])
    @briefcase.contents.delete(params[:super_power_id].to_s)
    flash[:notice] = "Successfully removed #{view_context.link_to(@super_power.title, super_power_path(@super_power)} from your briefcase."
    redirect_back(fallback_location: '/briefcase'
  end

end

The link_to helper is not rendering a link to the browser, rather it's printing the html: Successfully removed <a href=\"/powers/1\>flying</a> from your briefcase. I've also tried using the method #html_safe on the flash message to no avail. I'm wondering if there's a way to fix this using view_context or if there's a better way to include a link inside a Flash message.


Solution

  • You need to use html_safe when outputting the flash messages - not when storing them.

    <% flash.each do |key, msg| -%>
      <%= content_tag :div, msg.html_safe, class: name %>
    <% end -%>
    

    .html_safe just sets a flag on the string object that its trusted and should not be escaped.

    The flash works by storing flash messages in the session storage - by default this means a cookie in the browser.

    So when you do:

    flash[:notice] = "foo"
    

    You're storing the raw string "foo" in a cookie* and its unpacked back into the session on the next request. But the string is not the same Ruby object - so the html_safe flag on the string object is not persistent.