【发布时间】:2020-01-26 18:58:01
【问题描述】:
我正在尝试做两件事:
- 当用户点击编辑链接/按钮时,使用 Ajax 呈现编辑表单
- 然后在编辑后点击更新链接/按钮,隐藏表单。
...但不幸的是,它的行为并非如此。它通过 Ajax 完美呈现表单,但是......
- 它在所有行上呈现表单。
- 编辑后点击更新并不会隐藏表单。
下面是代码:
控制器
before_action :set_clock_entry, only: [:edit, :update]
def edit
end
def update
respond_to do |format|
if @clock_entry.update(clock_entry_params)
format.js { flash.now[:notice] = 'Clock entry was successfully updated.' }
format.html { redirect_to @clock_entry, notice: 'Clock entry was successfully updated.' }
format.json { render :show, status: :ok, location: @clock_entry }
else
format.html { render :edit }
format.json { render json: @clock_entry.errors, status: :unprocessable_entity }
end
end
end
edit.html.erb
<h1>Editing Clock Entry</h1>
<%= render 'form', clock_entry: @clock_entry %>
<%= link_to 'Back', clock_entries_path %>
_form.html.erb
<%= simple_form_for clock_entry, remote: true do |f| %> # I am setting remote: true here
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<div class="form-inputs">
<%= f.input :purpose %>
</div>
<div class="form-actions">
<%= f.button :submit, class: 'btn btn-primary btn-block btn-lg' %>
</div>
<% end %>
edit.js.erb
$('#edit-clock-entry a').hide().parent().append("<%= j render 'form', clock_entry: @clock_entry %>")
html 编辑链接
<tr>
<td>
<div id="edit-clock-entry">
<%= link_to 'Edit', edit_clock_entry_path(clock_entry), remote: true %>
</div>
</td>
</tr>
这是图像 - 它呈现在所有 id 上
【问题讨论】:
-
edit-clock-entry 不应该是一个 id,因为它不会对每一行都是唯一的。您应该这样做,以便每行的 id 都是唯一的,例如:这将至少确保只有单击的行会打开和关闭。
标签: javascript jquery ruby-on-rails ajax ruby-on-rails-6