I’ve been using this a lot in one of our current projects.. it comes in pretty handy. just create a

<div id="message" style="display: none"></div>
in your view. Here is an example from our login page:



# this goes in your application_helper.rb
# call it from your layout like this:
#     <%= flash_for :error %>    
#     <%= flash_for :notice %>
#     <%= flash_for :success %>

  def flash_for symbol
    # <div id="flash_error" class="message-block error">
    #   text
    # </div>
      content_tag( :div, flash[symbol].to_s, :id => "flash_#{symbol}", :class => "message-block #{symbol}",
                   :style => flash[symbol] ? nil : 'display: none' )
  end

# this goes in your controller

   def login #http get, ajax post
    redirect_to home_url( current_user ) and return if user_logged_in? #already logged in?
    if request.xhr?
      raise "Please enter a valid email address." unless params[:user][:email] =~  /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
      raise "Please enter a password!" if params[:user][:password].blank?

      if user = User.authenticate( params[:user][:email], params[:user][:password] )
        ::ActionController::Base.session_options[:session_expires] = params[:user][:remember] ? 2.weeks.from_now : nil  # remember me for 2 weeks if checked
        login_user user
        ajax_redirect_to home_url(current_user)
      else
        session[:forgotten_email] = params[:user][:email]          
        raise "Incorrect email address or password." 
      end
    end
  rescue Exception => e
    handle_ajax_error e
  end

# this goes in application.rb
protected
  def ajax_redirect_to url
    url = url_for( url ) if url.is_a? Hash
    render :update do |page|
      page << "window.location = '#{url}'" 
    end
  end

  def handle_ajax_error e
    render :update do |page|
      page.flash_then_fade :error, "Error: <nobr>#{e.message}</nobr>" 
      page << "Element.scrollTo('flash_error');" 
    end
    logger.error "\n\n#{e.message}" 
    logger.info e.backtrace.join("\n")
  end  

# this goes in /lib directory in a file that gets loaded in environment.rb
module ActionView
  module Helpers
    module PrototypeHelper
      class JavaScriptGenerator
        module GeneratorMethods

          def flash_then_fade symbol, message, seconds=0, fadeout=1
            # update message text
            replace_html "flash_#{symbol}", message
            # hide all notices except current
            (%w[ error success notice ] - [ symbol.to_s ]).each do |sym|
              hide "flash_#{sym}" 
            end
            dom_id = "flash_#{symbol}" 
            visual_effect :highlight, dom_id, :duration => 2.0
            show dom_id
            if seconds.to_f > 0
              delay( seconds ) do
                visual_effect :fade, dom_id, :duration => fadeout
              end
            end
          end

        end
      end
    end
  end
end

verify all AJAX actions as XHR

put this in your controllers/application.rb

  def initialize *args
    ajax_actions = self.public_methods(false).grep(/^ajax/i)
    unless ajax_actions.empty?
      self.class.send :eval, <<-RUBY
      verify :xhr => true,
             :only => [#{ajax_actions.map(&:to_sym).join(', ')}],
             :render => {:text => '405 XHR only', :status => 405 }
      RUBY
    end
    super *args
  end

actionmailer ActionView ajax alphadecimal audio autotest BDD blocks capistrano ssh ruby controller css dashboard widget delegate dog puppy naming name DRM email obfuscation exceptions factory pattern filemerge find and replace finder fink fixtures fun gem google maps helper helpers imagemagick Intertrust javascript logo math meetup model openssl OS X patch Pioneer Electronics plugin polymorphism prototype.js rails rake rmagick RSA encryption ruby script shoulda subversion SyncTV TDD testing textmate tricks unique hashes unix shell validation view yaml zebra stripes