You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails中使用link_to传递ID实现发票详情跳转?

嘿,这问题我之前也碰到过!你的核心问题是嵌套路由需要两个参数,但你现在只传了客户对象,导致路由没法定位到具体的发票。

先看你的路由:customer_invoice GET /customers/:customer_id/invoices/:id(.:format) invoices#show,这条路由明确要求两个参数:customer_id和invoice的id。你之前的代码<%= link_to 'Details', customer_invoice_path(@customer) %>只传了@customer,Rails没法知道你要指向哪个发票,所以才会出现所有按钮都指向同一页面的情况。

正确的写法有两种:

  1. 显式传递两个对象:在遍历发票的循环里,同时传入客户对象和当前的发票对象:
    <%= link_to '详情', customer_invoice_path(@customer, invoice) %>
    
  2. 简洁的数组写法:Rails支持直接用数组来生成嵌套路由的路径,它会自动识别数组里的对象对应路由层级:
    <%= link_to '详情', [@customer, invoice] %>
    

完整的使用示例

假设你在客户的详情页面(app/views/customers/show.html.erb)展示该客户的所有发票,代码应该是这样的:

<h1><%= @customer.name %>的发票列表</h1>

<table>
  <thead>
    <tr>
      <th>发票编号</th>
      <th>金额</th>
      <th>操作</th>
    </tr>
  </thead>
  <tbody>
    <% @customer.invoices.each do |invoice| %>
      <tr>
        <td><%= invoice.invoice_number %></td>
        <td><%= number_to_currency(invoice.amount) %></td>
        <td>
          <%= link_to '详情', [@customer, invoice], class: 'btn btn-primary' %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>

这样每个「详情」按钮都会生成类似/customers/123/invoices/456的URL,准确指向对应发票的详情页啦!

内容的提问来源于stack exchange,提问作者Ilja KO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:56:41