我添加了bootstrap模式来编辑用户配置文件。它编辑用户配置文件,但当表单内容中出现错误时,它会重定向到localhost:3000 / user。如何在模式本身中出现错误?我为用户使用了devise gem。我做错了什么
_edit.html.erb
<div class="modal" id="EditProfileModal" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Edit user</h4>
</div>
<div class="modal-body">
<div class="container">
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: {method: :put}) do |f| %>
<%= devise_error_messages! %>
<div class="form-group">
<%= f.label :email %><br/>
<%= f.email_field :email, autofocus: true, :value => current_user.email %>
</div>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
<% end %>
<div class="form-group">
<%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br/>
<%= f.password_field :password, autocomplete: "off" %>
<% if @minimum_password_length %>
<br/>
<em><%= @minimum_password_length %> characters minimum</em>
<% end %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %><br/>
<%= f.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="form-group">
<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br/>
<%= f.password_field :current_password, autocomplete: "off" %>
</div>
<div class="actions">
<%= f.submit "Update" %>
</div>
<% end %>
<h3>Cancel my account</h3>
<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: {confirm: "Are you sure?"}, method: :delete %></p>
</div>
</div>
<div class="modal-footer">
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
标题
<% if user_signed_in? %>
<header>
<%= link_to "sign out", destroy_user_session_path, method: :delete %>
<%= link_to "Edit profile", '#EditProfileModal', {'data-toggle' => "modal"} %>
<div style="text-align: center">Signed in as <b><%= current_user.email %></b></div>
</header>
<%= render "devise/registrations/edit"%>
<% end %>
答案 0 :(得分:1)
表单提交总是强制页面重新加载。您可以通过ajax
请求提交表单来绕过此问题。在 Rails 中,您可以通过将选项remote: true
传递到form_for
来电来完成此操作。请记住,要正确处理服务器的响应,您需要处理javascript事件:
$('[selector]').on('ajax:success', function(e, data, status, xhr) {
// do something
})
答案 1 :(得分:0)
您需要使用ajax进行表单提交,并使用data-remote = true。 比你需要覆盖注册控制器的更新操作,
在更新操作中,您可以使用
检查是否有错误if resource.update_attributes(your_params)
redirect_to :back # else any where you want to redirect
else
respond_to :js
end
并在registrations / update.js.erb中添加显示错误的div。
$(".modal-body").prepend("<div><%= resource.errors %></div>")