提交后关闭模式 rails

getting modal to close after submission rails

我试图让我的模式在添加新位置并且用户按下提交按钮后关闭,但我似乎无法让它工作。我不知道我对 .js 所做的事情是错误的还是其他原因。总体而言,我对 rails 还很陌生,这确实是我的第一个网站,因此非常感谢您的帮助!谢谢!

理想情况下,它将关闭模式并刷新当前页面,以便在单击提交按钮时显示新位置。目前,它将位置提交给数据库,但我必须手动关闭模式并刷新页面以显示新位置。

这是我的位置index.html

<%= javascript_include_tag "form.js" %>
<%= link_to 'New Location', '#new_location_modal', 'data-toggle' => 'modal' %>

<div class="modal fade" id="new_location_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Create new location</h4>
      </div>
      <div class="modal-body">
        <%= render 'form', modal: true %>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div>

_form.html.erb:

<% modal ||= false %>
<% remote = modal ? true : false %>
<%= form_for(@location, multipart: true, remote: remote, html: {role: :form, 'data-model' => 'location', id: 'new_loc_form'}) do |f| %>
  <% if @location.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@location.errors.count, "error") %> prohibited this location from being saved:</h2>

      <ul>
      <% @location.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

<%# Added Bootstrap classes, and help-block container for error messages %>
  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>
  <div class="actions">
    <%= f.submit 'Submit' %>
  </div> 
<% end %>

form.js:

$('#new_loc_form').on('submit', function() {
  $('#new_location_modal').modal('hide');
}):

如果您的目的是刷新页面,请不要在表单中设置 remote: true。当提交表单时,控制器将调用重定向,页面将被刷新,模态框也会被隐藏。

如果您需要处理 remote 表单提交,您的控制器应该能够 respond_to js 请求。

在您的控制器中:

def create
  @location = Location.new(location_params)

  #your logic here

  respond_to do |format|
    format.html { redirect_to locations_path } #or wherever you want to redirect
    format.js {} #this will render create.js.erb
end

现在,在您的 create.js.erb 中,您可以访问新创建的 @location,您可以在其中将其附加到位置列表,然后关闭模式。观看 here 演示(与您最相关的是在视频播放 4 分钟后开始)。