Search code examples
ruby-on-railsruby-on-rails-3actioncontroller

Rails 3 / Controller / Flash hash


I want to be able to pass multiple messages to the flash hash, inside of my controller, and have them display nicely together, e.g., in a bulleted list. The way I've devised to do this is to create a helper function in my Application Controller, which formats an array into a bulleted list, which I then pass to, in my case, flash[:success]. This is clearly not the Rails Way because, i.a., my bulleted list gets encoded. That is, instead of getting:

  • Message 1
  • Message 2

I get:

<ul><li>Message 1</li><li>Message 2</li></ul>

I'm sure I could figure out a way to raw() the output, but isn't there a simple way to get something like this working? Perhaps there's an option to pass to flash[]? Something else?


Solution

  • I used render_to_string and a partial instead of a helper to achieve something similar.

    # app/controller/dogs_controller.rb
    def create
      @dog = Dog.new(params[:dog])
      @messages=[]
      if @dog.save
        @messages << "one"
        @messages << "two"
        flash[:notice] = render_to_string( :partial => "bulleted_flash")
        redirect_to(dogs_path)
      else
        render :action => 'new
      end
    end
    

    Then I format the array of flash messages in an HTML list

    # app/views/dogs/_bulleted_flash.html.erb
    <ol>
      <% @messages.each do |msg| %>
      <li><%= msg %></li>
      <% end %>
    </ol>
    

    Which produces the following HTML

    # http://0.0.0.0:3000/dogs
    <body>
      <div id="flash_notice">
        <ul>
          <li>one</li>
          <li>two</li>
        </ul>
      </div>
      ...
    </body>
    

    If you need to continue using a helper then I think you need to append the html_safe method to your string to prevent it from being encoded (which rails 3 does by default). Here is a question showing how to use html_safe in a similar fashion