Rails flash notice via ajax

Here is an example that I got working, thanks to Rich Peck’s answer. I needed to use flash.now to make sure the flash notice didn’t persist.

AJAX trigger in the view:

<%= link_to "Email report", users_path, remote: true %>

Controller:

# app/controllers/users_controller
class UsersController < ApplicationController

  def index
    # do some things here

    respond_to do |format|
      format.js { flash.now[:notice] = "Here is my flash notice" }
    end
  end
end

Rendered view:

# app/views/users/index.js.erb
$("#flash").html('<%= j render partial: "shared/notice_banner" %>');

where the flash notice is displayed in the layout:

# app/views/layouts/application.html.erb
<div id="flash">
  <% if notice.present? %>
    <%= render partial: "shared/notice_banner" %>
  <% end %>
</div>


# app/views/shared/_notice_banner.html.erb
<div data-alert class="alert-box">
  <%= notice %>
  <a href="#" class="close">&times;</a>
</div>

Leave a Comment