【问题标题】:Rails Edit action not updating and not work properly using AjaxRails Edit 操作未更新且使用 Ajax 无法正常工作
【发布时间】:2020-01-26 18:58:01
【问题描述】:

我正在尝试做两件事

  1. 当用户点击编辑链接/按钮时,使用 Ajax 呈现编辑表单
  2. 然后在编辑后点击更新链接/按钮,隐藏表单。

...但不幸的是,它的行为并非如此。它通过 Ajax 完美呈现表单,但是......

  1. 它在所有行上呈现表单。
  2. 编辑后点击更新并不会隐藏表单。

下面是代码:

控制器

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


【解决方案1】:

我把它全部/专用于@bkunzi01 在帖子下对问题/问题的评论,这就是帮助我解决它的原因。所以这就是我最终解决它的方法:

错误 1

因此,根据我之前提到的建议,我必须重新定义我的 edit.js.erb 文件以处理行中编辑的唯一 ID。所以我的 edit.js.erb 变成:

$('#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 变成:

$('.refresh').bind('ajax:success', function () {
    $(this).hide().parent();
})

这就是我现在在图片中显示的内容

日志还显示正确的记录已更新

这为我解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多