在每个xhr请求中完成ajax后,rails 5 + bootstrap 4 +渲染烤面包机

时间:2019-05-22 11:19:45

标签: javascript ruby-on-rails ruby bootstrap-4 ruby-on-rails-5

我正在使用rails 5.2和bootsrap 4.3(https://getbootstrap.com/docs/4.3/components/toasts/)。我想在设置flash消息的地方显示烤面包机弹出窗口。我不想在每个xhr请求中都替换Flash消息的一部分。我有一个类似

的部分
<% flash_class = { notice: 'info', warning: 'warning', error: 'danger', success: 'success' } %>
<% flash.each do |name, msg| %>
    <div class="toast fade show" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
      <div class="toast-header border-bottom-0 bg-<%= flash_class[name.to_sym] %> text-white">
        <%= msg %>
        <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close"><span aria-hidden="true" class="text-white">×</span></button>
      </div>
    </div>
  <% end %>
<% end %>
<script type="text/javascript">
  $('.toast').toast('show');
</script>

如果我在application.html.erb中添加JavaScript代码以呈现Flash消息 <script type="text/javascript"> $(document).ajaxSuccess(function(event){ <% flash_class = { notice: 'info', warning: 'warning', error: 'danger', success: 'success' } %> <% flash_hash = flash.first %> console.log("<%= flash.first %>") <% unless flash_hash.nil? %> var html = '<div class="toast fade show" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000"><div class="toast-header border-bottom-0 bg-<%= flash_class[flash_hash[0].to_sym] %> text-white"><%= flash_hash[1] %><button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close"><span aria-hidden="true" class="text-white">×</span></button></div></div>' $('#toast-container').html(html); <% end %> }); </script>,但不会醒来,因为Flash变量的值过旧。

我已将after_action放入ApplicationController

after_action :render_flash

  def render_flash
    if request.xhr? && flash.present?
      render partial: "shared/flash_messages"
    end
  end

但是它给了我AbstractController::DoubleRenderError (Render and/or redirect were called multiple times

我该如何解决?有人有主意吗?

预先感谢

0 个答案:

没有答案