首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >提交rails后使模态关闭

提交rails后使模态关闭
EN

Stack Overflow用户
提问于 2015-07-06 17:04:50
回答 1查看 5.7K关注 0票数 0

我试图让我的模式关闭,一旦一个新的位置被添加到它和用户按下提交按钮,但我似乎无法使它工作。我不知道我对.js做了什么是错的还是其他的。我是相当新的rails作为一个整体,这是我的第一个网站,所以任何帮助都是非常感谢的!谢谢!

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

这是我的位置index.html

代码语言:javascript
复制
<%= 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:

代码语言:javascript
复制
<% 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:

代码语言:javascript
复制
$('#new_loc_form').on('submit', function() {
  $('#new_location_modal').modal('hide');
}):
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-06 18:05:09

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

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

在您的控制器中:

代码语言:javascript
复制
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,在那里您可以将其附加到位置列表中,然后关闭模式。看一看这里的演示(最相关的是4分钟后开始的视频)。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31251649

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档