我有一份客户名单。每个客户都有一个链接,链接到客户页面并显示他的数据。
我想链接到在客户表下方的同一页面上呈现的部分内容。在用表格初始化“页面”时,应该加载一个带有“选择客户”之类的空白页面。
我的客户列表代码:
<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 %>
你能帮我一些想法吗?
最佳答案
您基本上希望使用 AJAX 来显示客户的详细信息。为此,您可以使用 remote: true
rails 为 link_to
提供的选项 helper 。我们接下来要做的事情:
div#current_customer
remote: true
到您的链接:<td><%= link_to 'Show', customer, remote: true %></td>
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
show
中响应 Javascript CustomersController
中的方法:respond_to do |format|
format.js {render layout: false} # Add this line to you respond_to block
end
show.js.erb
View ,它将在 respond_to :js
时处理前端更改将被调用(在这种情况下由 remote: true
触发)show.js.erb
它必须做什么(用你的部分替换 #current_customer
内容,使用正确的 @customer
):客户/show.js.erb
$("#current_customer").html("<%= escape_javascript(render partial: 'customers/show', locals: { customer: @customer } ) %>");
客户/index.html.erb姓名
行动
<div id="current_customer"> # This will will contain the partial
</div>
关于ruby-on-rails - 使用 AJAX 单击 link_to 后如何在同一页面上呈现部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35899433/