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 %>
Rails can render a raw file from an absolute path. This is useful for conditionally rendering static files like error pages. This renders the raw file (it doesn't support ERB or other handlers). By default it is rendered within the current layout.
Rendering is the ultimate goal of your Ruby on Rails application. You render a view, usually . html. erb files, which contain a mix of HMTL & Ruby code. A view is what the user sees.
By default, if you use the :text option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option.
A layout defines the surroundings of an HTML page. It's the place to define a common look and feel of your final output. Layout files reside in app/views/layouts. The process involves defining a layout template and then letting the controller know that it exists and to use it.
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.
Try
def bye @counter = 4 flash.now[:error] = "Your book was not found" render :index 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