Rails Edit操作无法更新,并且无法使用Ajax正常工作 [英] Rails Edit action not updating and not work properly using Ajax
问题描述
我正在尝试做两件事:
- 当用户单击编辑"链接/按钮时,使用Ajax呈现编辑"表单
- 然后在编辑后,他们单击更新"链接/按钮,隐藏表单.
...但是不幸的是,它没有那样表现.它可以通过Ajax完美呈现表单,但是...
...but unfortunately, it didn't behave that way. It perfectly renders the form through Ajax but...
- 它在所有行上呈现表单.
- 编辑后,单击更新"不会隐藏表单.
下面是代码:
控制器
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上呈现
推荐答案
在问题/问题的帖子下,我全力以赴/献给@ bkunzi01的评论,这正是帮助我解决问题的原因.所以这就是我最终解决它的方式:
I give it all/dedicate it to @bkunzi01's comment under the post to the problem/question and that is what helped me solved it. So this is how I eventually solved it:
错误1 :
因此,根据我之前提到的建议,我必须重新定义我的edit.js.erb
文件以处理该行中唯一的编辑ID.因此,我的 edit.js.erb 变为:
So according to what was suggested as I mentioned earlier, I had to redefine my edit.js.erb
file to handle unique id of the edit in the row. So my edit.js.erb becomes:
$('#edit-clock-entry-<%= @clock_entry.id %> a').hide().parent().append("<%= j render 'form', clock_entry: @clock_entry %>")
错误2 :
我没有使用ajax创建更新操作,这使得它的行为与行为相同.因此,我创建了一个名为update.js.erb
的文件来处理用户单击更新按钮时发生的情况.因此,我的 update.js.erb 变为:
I did not create update action with ajax and that made it behaved the way it behaved. So I created a file called update.js.erb
to handle what happens when users hit the update button. So my update.js.erb becomes:
$('.refresh').bind('ajax:success', function () {
$(this).hide().parent();
})
这就是我现在在图片中显示的内容
日志还显示正确的记录已更新
这为我解决了.
这篇关于Rails Edit操作无法更新,并且无法使用Ajax正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!