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="#">×</a>
<%= content_tag :p, flash[:notice] %>
</div>
<% end %>
Things I don’t like:
- Maybe it’s anal, but I would prefer to not render
<div id="jsflash"></div>unless I absolutely have to. - 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. - The
<% flash.clear %>, likewise, it’s a confusion of roles, with the view driving application state. - It seems like there should be some facility for this already. Have I overlooked something?
<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 yourApplication.rb.
2.3.4. I’ve never had to use
flash.clearin the dozens of flash applications I have made. You also seem to have some unneeded duplication here with your flash calls.