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

mah*_*ahu 6 ajax asynchronous ruby-on-rails 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" %>
Run Code Online (Sandbox Code Playgroud)

我部分用于展示客户:

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

<%= link_to 'Edit Customer', edit_customer_path(@customer) %> |
<%= link_to 'Back', customers_path %>
Run Code Online (Sandbox Code Playgroud)

你能帮我一些想法吗?

Kar*_*bit 14

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

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

    <td><%= link_to 'Show', customer, remote: true %></td>
    
    Run Code Online (Sandbox Code Playgroud)
  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
    
    Run Code Online (Sandbox Code Playgroud)
  4. 在以下show方法中响应Javascript CustomersController:

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

  6. 告诉show.js.erb它必须做什么(#current_customer用你的部分替换内容,使用右边@customer):

客户/ show.js.erb

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

客户/ index.html.erb

<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, remote: true %></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" %>

<div id="current_customer"> # This will will contain the partial 
</div>
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用。我正在使用 Rails 6。 (2认同)