打开Bootstrap Modal以编辑Ruby on Rails中的记录

我有一个“用户”模型。 我在用户索引页面上有一个用户列表,每个用户旁边都有一个编辑按钮。 我想点击每个用户的编辑按钮,这将打开一个bootstrap模式。

在bootstrap模式上,我想显示我可以编辑的用户记录。 编辑表单将来自_form.html.erb部分,该部分将用于新的和编辑用户控制器方法。

当我单击更新按钮时,我希望模态窗体更新记录,关闭模式并使用更新的记录更新索引页。

问题

  1. 每次我点击编辑链接时,模态都会打开并显示_forms部分,但它是用于新记录,而不是我想要编辑的记录。 我认为这是因为rails运行@ user.persisted? 响应为false的助手,因此它使用用户控制器中的“创建”方法而不是“编辑”方法。

  2. 保存记录时,引导模式不会关闭。

你能告诉我如何让它发挥作用吗?

用户/ _form.html.erb

  

prohibited this user from being saved:




用户/ create.js.erb

 $(".usersTable").replaceWith(" 'users/update_user', :locals => {users: @users }%>"); $("input[type=text]").val(""); $('#myModal').modal('hide'); $('body').removeClass('modal-open'); $('.modal-backdrop').remove(); 

用户/ index.html.erb

 

Listing users

Name Company Email
'#myModal', 'data-toggle' => 'modal' %>

/controllers/users_controller.rb

 class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] # GET /users # GET /users.json def index @users = User.all @user = User.new end # GET /users/1 # GET /users/1.json def show end # GET /users/new def new @user = User.new end # GET /users/1/edit def edit @user = User.find(params[:id]) end # PATCH/PUT /users/1 # PATCH/PUT /users/1.json def update respond_to do |format| if @user.update(user_params) format.js {} else format.html { render action: 'edit' } format.json { render json: @user.errors, status: :unprocessable_entity } end end end 

当前表单不用于编辑记录,将其更改为:

用户/ index.html.erb

 

Listing users

<% @users.each do |user| %> <% end %>
Name Company Email
<%= user.name %> <%= user.company %> <%= user.email %> <%= link_to 'Show', user %> <%= link_to 'Edit', '#', 'data-target' => "#myModal_#{user.id}", 'data-toggle' => 'modal' %> <%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %>

用户/ _form.html.erb

 <%= form_for(user, remote: true) do |f| %> <% if @user.errors.any? %> 

<%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:

    <% @user.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>
<% end %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :company %>
<%= f.text_field :company %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.submit %>
<% end %>

如果要单击提交以刷新整个页面,只需从_form.html.erb中删除remote:true即可

@aquajach为您提供了解决第一个问题的正确代码。 请注意,您的问题出现是因为您没有将’user’参数发送到表单partial,而是使用@user来构建表单,这是您在index操作中使用new初始化的变量(因此它是空的)。 当@aquajach发送正确的参数时,您需要将模态代码放在`.each’循环中,否则无法告诉您希望每个模态显示哪个用户的信息。

另请注意,编辑link_to使用“#”作为其URL。 这意味着它将链接到无处,并且绝对不会返回到服务器上的控制器(既不编辑也不创建)。

至于你的第二个问题。 请注意,“关闭”按钮具有data-dismiss="modal" ,但“保存更改”按钮则没有。 附加该代码,以使其隐藏模态。