【问题标题】:Ajax edit page in index索引中的 Ajax 编辑页面
【发布时间】:2013-09-01 10:01:20
【问题描述】:

我有这个页面索引页面:

<h1>Listing users</h1>

<table border="1">
  <tr>
    <th>Name</th>
    <th>Description</th>
    <th>Who</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @users.each do |user| %>
  <tr>
    <td><%= user.name %></td>
    <td><%= user.description %></td>
    <td><%= user.who %></td>
    <%= render 'users/form' %>
    <td><%= link_to 'Show', user %></td>
    <td><%= link_to 'Edit', edit_user_path(user) %></td>
    <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New User', new_user_path %>

脚手架控制器

def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @users }
    end
  end

我需要在索引页面编辑用户,而不是去 url /users/2/edit,留在用户页面。

我如何在 Ajax 中做到这一点?

【问题讨论】:

    标签: ruby-on-rails ajax ruby-on-rails-3


    【解决方案1】:

    remote:true 添加到Edit 行以进行ajax 调用:

    <td><%= link_to 'Edit', edit_user_path(user), remote:true %></td>
    

    另外,添加一个edit.js.erb 文件(一个嵌入了 ruby​​ 的 javascript 文件),您可以在其中执行所有要在Edit 之后执行的 javascript 操作。 edit.js.erb 文件是在 edit 方法完成时生成的。您可以在此处编写对影响当前页面的 javascript 代码的所有更改(该页面不会重新呈现)。

    另外,将以下内容添加到edit 方法中:

    respond_to do |format|
       format.js
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 2019-11-01
      • 2014-05-04
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多