我有一个客户列表。每个客户都有一个链接,链接到客户页面并显示他的数据。
我想链接到客户表下方同一页面上呈现的部分内容。在使用表格初始化“页面”时,应加载一个类似“选择客户”的空白页面。
我的客户列表代码:
<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 %>
你能帮助我一些想法吗?
答案 0 :(得分:14)
您基本上想要使用AJAX来显示客户的详细信息。为此,您可以使用rails提供的remote: true
选项来link_to
帮助程序。我们接下来要做什么:
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
的{{1}}方法中回复Javascript:
CustomersController
创建respond_to do |format|
format.js {render layout: false} # Add this line to you respond_to block
end
视图,该视图将在show.js.erb
被调用时处理前端更改(在这种情况下由respond_to :js
触发)
告诉show.js.erb它必须做什么(使用右侧remote: true
替换{partial} #current_customer
内容:
@customer
$("#current_customer").html("<%= escape_javascript(render partial: 'customers/show', locals: { customer: @customer } ) %>");