如何在使用AJAX单击link_to后在同一页面上呈现部分

时间:2016-03-09 18:15:15

标签: ruby-on-rails ajax asynchronous partial

我有一个客户列表。每个客户都有一个链接,链接到客户页面并显示他的数据。

我想链接到客户表下方同一页面上呈现的部分内容。在使用表格初始化“页面”时,应加载一个类似“选择客户”的空白页面。

我的客户列表代码:

<h1>Listing Customers</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th colspan="3">Actions</th>
    </tr>
  </thead>

  <tbody>
    <% @customers.each do |customer| %>
      <tr>
        <td><%= customer.name %></td>
        <td><%= link_to 'Show', customer %></td>
        <td><%= link_to 'Edit', edit_customer_path(customer) %></td>
        <td><%= link_to 'Destroy', customer, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>

  </tbody>
</table>

<br>

<%= link_to 'New Customer', new_customer_path, class: "button", id: "new_customer" %>

我部分展示客户:

<p>
  <strong>Name:</strong>
  <%= @customer.name %>
  <%= @customer.id %>
</p>

<%= link_to 'Edit Customer', edit_customer_path(@customer) %> |
<%= link_to 'Back', customers_path %>

你能帮助我一些想法吗?

1 个答案:

答案 0 :(得分:14)

您基本上想要使用AJAX来显示客户的详细信息。为此,您可以使用rails提供的remote: true选项来link_to帮助程序。我们接下来要做什么:

  1. 创建一个包含已加载数据的div。在这种情况下div#current_customer
  2. remote: true添加到您的链接:

    <td><%= link_to 'Show', customer, remote: true %></td>
    
  3. 为您的部分customers/_show.html.erb命名(不要忘记_,以便可以将其称为部分):

    <p>
       <strong>Name:</strong>
       <%= @customer.name %>
       <%= @customer.id %>
    </p>
    
    <%= link_to 'Edit Customer', edit_customer_path(@customer) %> |
    <%= link_to 'Back', customers_path %> # You should remove this link
    
  4. show的{​​{1}}方法中回复Javascript:

    CustomersController
  5. 创建respond_to do |format| format.js {render layout: false} # Add this line to you respond_to block end 视图,该视图将在show.js.erb被调用时处理前端更改(在这种情况下由respond_to :js触发)

  6. 告诉show.js.erb它必须做什么(使用右侧remote: true替换{partial} #current_customer内容:

  7. 客户/ show.js.erb

    @customer

    客户/ index.html.erb

    $("#current_customer").html("<%= escape_javascript(render partial: 'customers/show', locals: { customer: @customer } ) %>");