The use of :alert (or :notice) with the render method, from the Ruby On Rails guide called 'Layouts and Rendering in Rails', does not work for me:

Caroline Schnapp picture Caroline Schnapp · Mar 3, 2013 · Viewed 35.9k times · Source

The use of :alert (or :notice) with the render method, from the Ruby On Rails guide called 'Layouts and Rendering in Rails' at http://guides.rubyonrails.org/layouts_and_rendering.html, does not work for me

That's the sample code provided in the guide:

    def index
      @books = Book.all
    end

    def show
      @book = Book.find_by_id(params[:id])
      if @book.nil?
        @books = Book.all
        render "index", :alert => 'Your book was not found!'
      end
    end

I have a hello controller that looks like this:

    class HelloController < ApplicationController
      def index
        @counter = 5
      end
      def bye
        @counter = 4
        render "index", :alert => 'Alert message!'
      end
    end

My index.html.erb view looks like that:

    <ul>
    <% @counter.times do |i| %>
      <li><%= i %></li>
    <% end %>
    </ul>

When accessing http://localhost:3000/hello/bye, I see the index view, i.e. a list of numbers from 1 to 4 as expected, but there's no 'Alert message!' alert showing.

My layout uses this to show alert messages:

    <% flash.each do |k, v| %>
      <div id="<%= k %>"><%= v %></div>
    <% end %>

Answer

Dan Wich picture Dan Wich · Mar 3, 2013

I'm confused as to why that Rails Guide mentions using flash values in render, since they only appear to work in redirect_to at the moment. I think you'll find your approach works if you put a flash.now[:alert] = 'Alert message!' before your render method call.

Edit: this is a flaw in the guides that will be fixed, you should use the separate method call to set the flash prior to calling render.