title: Need a way for Rails controller to return flash messages in response to AJAX request
body: <p>As an inexperienced but quick-learning Rails developer, I want to write a controller after-filter that checks for AJAX requests and returns some HTML in a custom header that can be used by the response handler to display any flash messages.  </p>
  
  <p>For consistency and conformance to DRY, I want to create that partial HTML using the same app/views/layouts/_messages.html.erb(.haml) that Rails generated.</p>
  
  <p>After viewing several posts, my solution is thus:</p>
  
  <pre><code>  # adapted from http://stackoverflow.com/a/2729454/270511
    def flash_to_headers
      return unless request.xhr?
      response.headers['X-flash'] = render_to_string partial: 'layouts/messages.html'
      flash.discard  # don't want the flash to appear when you reload page
    end
  </code></pre>
  
  <p>This actually returns the desired headers, but also <a href="https://gist.github.com/lsiden/8773448" rel="nofollow">throws an exception</a>.</p>
  
  <p>Subsequent searching revealed several posts where the respondents claimed that calling render_to_string from an after-filter is not supported.</p>
  
  <p>One alternate solution I am thinking of is to render layouts/navigation.html a second time from views/layouts/application.html.haml, but enclosed in a div where display=none.  To accomplish this with the same template, I will have to add some dummy place-holder messages to flash[:notice, :warn, and :error] because otherwise _messages.html.haml was written not to render sections when there are no related messages.  Then I can use the placeholders as templates to clone and fill in with flash messages returned by subsequent AJAX requests.</p>
  
  <p>While this might work, I think it is ugly and has an unpleasant smell.  (I am inexperienced at Rails, but not at software development!)  It may be possible that I have missed something due to my lack of experience with Rails (and lack of available mentors).  If so, I will be grateful if someone can point out a cleaner way of accomplishing my goal.</p>
  
  <p>If not, I will re-post this to the issues list for rails on Github.  I think that displaying flash messages to indicate some feedback from an AJAX request to the end-user is a common enough use-case that Rails should support it better.  </p>