In Rails, is it possible to display an alert without calling redirect_to or render?

后端 未结 1 1750
忘掉有多难
忘掉有多难 2021-01-27 13:03

I have a form:

<%= form_tag generate_report_path(:header => true) do |f| % >
相关标签:
1条回答
  • 2021-01-27 13:49

    You should use remote: true in your form.

    <%= form_tag generate_report_path(:header => true), remote: true do |f| % >
    <div class="container-fluid">
      <div style="padding-right:10px">
       <%= select_tag(:report_id, options_for_select(
          [["Select Report Type", 0],
          ["Report1", 1],
          ["Report2", 2],
          ["Report3", 3]]), id: "report_selection") 
       %>
       <%= hidden_field_tag :format, :pdf %>
       <%= button_tag "Generate Report", class: 'btn btn-sm btn-primary'%>
       <%= label_tag do %>
         <%= check_box_tag "format_reqd", "format_reqd", false %>
         Check for Numeric format 
       <% end %>
    
    <% end  %>
    

    Above remote: true is responsible for sending ajax request to your controller method. Here is a complete guide for form_for and remote requests.

    In your method of the controller:

    def generate_report
      ... #Whatever you want to add here.
      render js: "alert('Your report would be emailed to you in a few minutes')"
    end
    

    Update with the flash message:

    Your controller method will now look like:

    def generate_report
      ... #Whatever you want to add here.
      respond_to do |format|
        format.js { flash[:notice] = "Your report would be emailed to you in a few minutes" }
      end
    end
    

    Rendered view:

    # app/views/users/generate_report.js.erb
    $("#flash").html('<%= j render partial: "shared/notice_banner" %>');
    
    
    # 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>
    
    

    Here is the detailed answer present. Hope this will help.

    0 讨论(0)
提交回复
热议问题