This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This gist shows how to display Rails like flash messages while handling AJAX or JS requests | |
# Note - This might not be the best way to do this but it works for me | |
Step 1. Create a partial which will contain the message to be displayed | |
Example - _success.html.erb | |
<div id="flash_message"> | |
<p>Success</p> | |
</div> | |
Step 2. In the Controller, add code to call this partial on a JS request | |
Example - ExampleController.rb | |
class ExampleController < ApplicationController | |
. | |
. | |
. | |
def example_action | |
. | |
. | |
respond_to |format| | |
# This call will search for action success, if not present, it will call the template named success.js | |
# Note - success.js is created in step 3 | |
format.js { render :action => 'success' if some_condition } | |
end | |
end | |
end | |
Step 3. Create a file called success.js which will render the flash message | |
Example - success.js.erb | |
$("#element_where_flash_to_appear").prepend( | |
$("<%= escape_javascript(render :partial => 'success') %>"). | |
hide().fadeIn(1000, function(){ | |
$(this).remove(); | |
}) | |
); | |
Step 4. CSS for flash message | |
#flash_message { | |
text-align: center; | |
background: #ffe; | |
width:100%; | |
margin-left:auto; | |
margin-right:auto; | |
border:1px solid gray; | |
margin:0px; | |
} |