В Rails можно ли отобразить предупреждение без вызова redirect_to или render? - PullRequest
0 голосов
/ 24 июня 2019

У меня есть форма:

<%= form_tag generate_report_path(:header => 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 %>

Когда пользователь устанавливает флажок и нажимает кнопку Generate Report, я хотел бы отобразить предупреждение для пользователя: «Ваш отчет будет отправлен вам по электронной почте через несколько минут»; но страница не должна обновляться.

Как мне достичь этих двух:

  1. Отключить обновление страницы?
  2. Показать флэш-сообщение?

Пожалуйста, помогите!

UPDATE:

  1. Я добавил это в свой контроллер (называемый report_controller):
    def reportgen

            respond_to do |format|
              format.js { flash.now[:alert] = "Report generation has been initiated. You will receive an email in approximately 4 - 5 minutes with a link to download the report."}
            end

    end
  1. \app\views\report\reportgen.js.erb
    $("#flash").html('<%= j render partial: "shared/notice_banner" %>');
  1. application.html.erb
  <div id="flash">
    <% if alert.present? %>
      <%= render partial: "shared/notice_banner" %>
    <% end %>
  </div>

  <% flash.each do |key, value| %>
    <% if key.to_s == "alert" %>
      <div style= "color: #FF0000" class="text-center <%= flash_class(key) %>">
      <%= value %>
    </div>
    <% else %>
      <div class="lead text-center <%= flash_class(key) %>">
      <%= value %>
    </div>
    <% end %>    
  <% end %>



  <%= yield %>
  1. app\views\shared\_notice_banner.html.erb
<div data-alert class="alert-box">
  <%= alert %>
  <a href="#" class="close">&times;</a>
</div>
  1. И это мой код для добавления кнопки и флажка в моей форме:
                  <div id="generate_button" style="display: none; float:left;">
                    <%= button_tag "Generate Report", class: 'btn btn-sm btn-primary'%>
                  </div>
                  &nbsp;
                  <div id="report_type_drop" style="display: none;padding-top:5px;padding-left:5px">


                    <%= label_tag do %>
                      <%= check_box_tag "format_reqd", "format_reqd", false %>
                      Check for Numeric format
                    <% end %>
                    </div>

С приведенным выше кодом вот результаты для моих 2 вопросов в моем первоначальном вопросе прямо сейчас:

  1. Отключить обновление страницы - теперь это прекрасно работает
  2. Отображение флеш-сообщения - это не работает!

UPDATE:

Я также вижу эту ошибку сейчас (хотя я не уверен, что это вызывает):

ActionController::UnknownFormat (ReportController#reportgen is missing a template for this request format and variant.

request.formats: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]
request.variant: []):

actionpack (5.0.7.1) lib/action_controller/metal/implicit_render.rb:43:in `default_render'
actionpack (5.0.7.1) lib/action_controller/metal/basic_implicit_render.rb:4:in `block in send_action'
actionpack (5.0.7.1) lib/action_controller/metal/basic_implicit_render.rb:4:in `tap'
actionpack (5.0.7.1) lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action'
actionpack (5.0.7.1) lib/abstract_controller/base.rb:188:in `process_action'
actionpack (5.0.7.1) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (5.0.7.1) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:126:in `call'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:506:in `block (2 levels) in compile'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:455:in `call'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:448:in `block (2 levels) in around'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:286:in `block (2 levels) in halting'
audited (4.8.0) lib/audited/sweeper.rb:14:in `around'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:405:in `public_send'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:405:in `block in make_lambda'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:285:in `block in halting'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:447:in `block in around'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:455:in `call'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:448:in `block (2 levels) in around'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:286:in `block (2 levels) in halting'
audited (4.8.0) lib/audited/sweeper.rb:14:in `around'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:405:in `public_send'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:405:in `block in make_lambda'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:285:in `block in halting'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:447:in `block in around'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:455:in `call'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:101:in `__run_callbacks__'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:750:in `_run_process_action_callbacks'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:90:in `run_callbacks'
actionpack (5.0.7.1) lib/abstract_controller/callbacks.rb:19:in `process_action'
actionpack (5.0.7.1) lib/action_controller/metal/rescue.rb:20:in `process_action'
actionpack (5.0.7.1) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
activesupport (5.0.7.1) lib/active_support/notifications.rb:164:in `block in instrument'
activesupport (5.0.7.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (5.0.7.1) lib/active_support/notifications.rb:164:in `instrument'
actionpack (5.0.7.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
actionpack (5.0.7.1) lib/action_controller/metal/params_wrapper.rb:248:in `process_action'
activerecord (5.0.7.1) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
actionpack (5.0.7.1) lib/abstract_controller/base.rb:126:in `process'
actionview (5.0.7.1) lib/action_view/rendering.rb:30:in `process'
actionpack (5.0.7.1) lib/action_controller/metal.rb:190:in `dispatch'
actionpack (5.0.7.1) lib/action_controller/metal.rb:262:in `dispatch'
actionpack (5.0.7.1) lib/action_dispatch/routing/route_set.rb:50:in `dispatch'
actionpack (5.0.7.1) lib/action_dispatch/routing/route_set.rb:32:in `serve'
actionpack (5.0.7.1) lib/action_dispatch/journey/router.rb:39:in `block in serve'
actionpack (5.0.7.1) lib/action_dispatch/journey/router.rb:26:in `each'
actionpack (5.0.7.1) lib/action_dispatch/journey/router.rb:26:in `serve'
actionpack (5.0.7.1) lib/action_dispatch/routing/route_set.rb:727:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
omniauth (1.4.2) lib/omniauth/strategy.rb:186:in `call!'
omniauth (1.4.2) lib/omniauth/strategy.rb:164:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/rack/agent_hooks.rb:30:in `traced_call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/rack/browser_monitoring.rb:32:in `traced_call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
rack (2.0.6) lib/rack/etag.rb:25:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
rack (2.0.6) lib/rack/conditional_get.rb:38:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
rack (2.0.6) lib/rack/head.rb:12:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
rack (2.0.6) lib/rack/session/abstract/id.rb:232:in `context'
rack (2.0.6) lib/rack/session/abstract/id.rb:226:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
actionpack (5.0.7.1) lib/action_dispatch/middleware/cookies.rb:613:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
activerecord (5.0.7.1) lib/active_record/migration.rb:553:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
actionpack (5.0.7.1) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:97:in `__run_callbacks__'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:750:in `_run_call_callbacks'
activesupport (5.0.7.1) lib/active_support/callbacks.rb:90:in `run_callbacks'
actionpack (5.0.7.1) lib/action_dispatch/middleware/callbacks.rb:36:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
actionpack (5.0.7.1) lib/action_dispatch/middleware/executor.rb:12:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
actionpack (5.0.7.1) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
actionpack (5.0.7.1) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
web-console (3.7.0) lib/web_console/middleware.rb:135:in `call_app'
web-console (3.7.0) lib/web_console/middleware.rb:22:in `block in call'
web-console (3.7.0) lib/web_console/middleware.rb:20:in `catch'
web-console (3.7.0) lib/web_console/middleware.rb:20:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
actionpack (5.0.7.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
railties (5.0.7.1) lib/rails/rack/logger.rb:36:in `call_app'
railties (5.0.7.1) lib/rails/rack/logger.rb:24:in `block in call'
activesupport (5.0.7.1) lib/active_support/tagged_logging.rb:69:in `block in tagged'
activesupport (5.0.7.1) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (5.0.7.1) lib/active_support/tagged_logging.rb:69:in `tagged'
railties (5.0.7.1) lib/rails/rack/logger.rb:24:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
actionpack (5.0.7.1) lib/action_dispatch/middleware/request_id.rb:24:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
rack (2.0.6) lib/rack/method_override.rb:22:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
rack (2.0.6) lib/rack/runtime.rb:22:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
activesupport (5.0.7.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
actionpack (5.0.7.1) lib/action_dispatch/middleware/executor.rb:12:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
actionpack (5.0.7.1) lib/action_dispatch/middleware/static.rb:136:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
rack (2.0.6) lib/rack/sendfile.rb:111:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
railties (5.0.7.1) lib/rails/engine.rb:522:in `call'
newrelic_rpm (6.3.0.355) lib/new_relic/agent/instrumentation/middleware_tracing.rb:99:in `call'
puma (3.12.0) lib/puma/configuration.rb:225:in `call'
puma (3.12.0) lib/puma/server.rb:658:in `handle_request'
puma (3.12.0) lib/puma/server.rb:472:in `process_client'
puma (3.12.0) lib/puma/server.rb:332:in `block in run'
puma (3.12.0) lib/puma/thread_pool.rb:133:in `block in spawn_thread'

ОБНОВЛЕНИЕ: (обновление 3)

Если я изменю код моего контроллера на это:

  • вышеприведенная ошибка трассировки стека исчезает
  • обновление страницы не происходит - это хорошо
  • но флэш-сообщение все еще не появляется
            respond_to do |format|
              format.json { flash.now[:alert] = "Report generation has been initiated. You will receive an email in approximately 4 - 5 minutes with a link to download the report."}
            end

1 Ответ

2 голосов
/ 24 июня 2019

Вы должны использовать remote: true в своей форме.

<%= 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  %>

Выше remote: true отвечает за отправку ajax-запроса на ваш Контроллер метод. Вот полное руководство для form_for и удаленного запросы.

В вашем методе контроллера:

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

Обновление с помощью флэш-сообщения:

Ваш метод контроллера теперь будет выглядеть так:

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

Представление:

# 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>

Здесь - подробный ответ. Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...