Rails flash notice via ajax

后端 未结 2 464
北海茫月
北海茫月 2020-11-29 00:55

Long story short, I have a button. On clicking it, I want an ajax request to be triggered which gets flash[:notice] and displays it in a div in$

Here is my shortened

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 01:37

    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
    
    <% if notice.present? %> <%= render partial: "shared/notice_banner" %> <% end %>
    # app/views/shared/_notice_banner.html.erb
    <%= notice %> ×

提交回复
热议问题