Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Rails3 Flash messages between format.html and format.js?

I would like to share FlashHash notices more cleanly between plain-old HTTP users and UJS folks that I've been able to contrive. Allow me to show you what I have first:

First, part of the respond_to section of the relevant controller's #update:

respond_to do |format|
  if @cont.save
    flash[:notice] = 'Continent was successfully updated.'
    format.html { redirect_to edit_continent_url(@cont) }
    format.json { head :ok }
    format.js

and an update.js.erb to match it:

$('#jsflash').html('<%= escape_javascript(render :partial => "application/notices/notice") %>').show();
<% flash.clear %> # clear the flash to avoid displaying on page reloads

Likewise in my application.html.erb there is

<div id="jsflash"></div>
<%= render "application/notice/alert" %>

and app/views/application/notices/_notice.html.erb:

<% unless flash[:notice].blank? %>
  <div class="alert-message info fade in" data-alert="alert">
    <a class="close" href="#">&times;</a>
    <%= content_tag :p, flash[:notice] %>
  </div>
<% end %>

Things I don't like:

  1. Maybe it's anal, but I would prefer to not render <div id="jsflash"></div> unless I absolutely have to.
  2. The <% flash.clear %> in the update js exists to clear flash out in case of page reload. However, that's going to get really tedious and error-prone as each JS view will need to have this but might forget to include it.
  3. The <% flash.clear %>, likewise, it's a confusion of roles, with the view driving application state.
  4. It seems like there should be some facility for this already. Have I overlooked something?
like image 891
troutwine Avatar asked Jan 19 '26 23:01

troutwine


1 Answers

  1. To avoid rendering <div id="jsflash"></div> when its not needed you will want to wrap the flash block in an if statement. You could put something like this in your Application.rb

.

 <% if flash.present? %>
   //Call your Render Flash Here
 <% end %>

2.3.4. I've never had to use flash.clear in the dozens of flash applications I have made. You also seem to have some unneeded duplication here with your flash calls.

like image 151
Justin Herrick Avatar answered Jan 21 '26 13:01

Justin Herrick