In case you want to use AJAX calls redirect_to should not be used in the controller. Rather, flash message should be explicitly denoted:
In your_controller:
respond_to :js
def your_ajax_method
flash[:notice] = 'Your message!'
end
In the view that is named by your_ajax_method_in_the_controller
your_ajax_method_in_the_controller.js.haml
:plain
$("form[data-remote]")
.on("ajax:success", function(e, data, status, xhr) {
$('.messages').html("#{escape_javascript(render 'layouts/messages')}");
setTimeout(function(){ $(".alert").alert('close') }, 5000);
})
Please, notice, that the messages class is an anchor point for rendering messages. This class should be present in your view or application layout. If you use ERB the line becomes $('.messages').html("<%= j(render 'layouts/messages') %>");
The above JavaScript embedded into HAML/ERB is the key to displaying flash messages when using AJAX. All other components remain the same for non-AJAX calls.
You may use your_ajax_method_in_the_controller.js.coffee
or plain .js but then the rails variables won't be available to JS/Coffee. Even though I don't use variables here I prefer to wrap JS in HAML to keep consistent codebase.
I leverage Twitter Bootstrap for styling messages, thus $(".alert").alert('close')
fades away the notice. And here is the messages partial:
layouts/_messages.html.haml
- flash.each do |name, msg|
- if msg.is_a?(String)
.alert-messages
%div{class: "alert alert-#{name == :notice ? "success" : "error"} fade in"}
%a.close{"data-dismiss" => "alert"}
%i.icon-remove-circle
= content_tag :div, msg, id: "flash_#{name}"
Just in case, CSS for the alerts is below
.alert-messages {
position: fixed;
top: 37px;
left: 30%;
right: 30%;
z-index: 7000;
}