Ajax编辑索引中的页面



我有这个页面索引页面:

<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中做到这一点的?

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

最新更新