2016-03-10 41 views
0

我想从我的/clients/:client_idshow页面链接到现有路由/clients/:client_id/invoices/:id 并不能工作如何做到以正确的路由。无法链接使用的link_to

我有一个has_many through:关系,这里是我models

class Client < ActiveRecord::Base 
has_many :invoices 
has_many :items, through: :invoices 

class Invoice < ActiveRecord::Base 
belongs_to :user 
belongs_to :client 
has_many :items, :dependent => :destroy 

accepts_nested_attributes_for :items, :reject_if => :all_blank, :allow_destroy => true 

class Item < ActiveRecord::Base 
belongs_to :invoice 
belongs_to :client 

我的路线

resources :clients do 
resources :invoices 
end 
resources :invoices 

我的客户端控制器显示行动

def show 
@client = Client.find(params[:id]) 
@invoices = @client.invoices.build 
end 

而且我的客户show.html.erb

<div class="panel-body"> 
     <table class="table table-hover"> 
      <thead> 
      <tr> 
       <th>Sender</th> 
       <th>Reciever</th> 
       <th>Amount</th> 
       <th>Currency</th> 
       <th>Date</th> 
       <th colspan="3"></th> 
      </tr> 
      </thead>    
      <tbody>    
      <% @client.invoices.each do |invoice| %> 
       <tr> 
       <td><%= invoice.sender %></td> 
       <td><%= invoice.reciever %></td> 
       <td><%= invoice.amount %></td> 
       <td><%= invoice.currency %></td> 
       <td><%= invoice.date %></td> 
       <td><%= link_to 'Show', invoices_path(@clients, @invoice) %></td> 
       </tr>     
      <% end %> 
      </tbody> 
     </table> 
     </div> 

每次我点击link_to show其路由我/invoices 我已经尝试了一堆不同link_to格式,但我一直没能弄明白。

回答

2

您正在使用错误的url_helper和错误的参数。你应该有:

<td><%= link_to 'Show', client_invoice_path(@client, invoice) %></td> 

<td><%= link_to 'Show', invoice_path(invoice) %></td> 

invoices_pathresources :invoices(最外面的)产生url_helper和意志路线,你为你的InvoicesController(/invoices)的索引路径。如果你传递一个参数,它将被用于格式(/invoices.10 - 很常见的问题)。

嵌套resources生成的所有路由的名称都由两个资源组成,如new_user_profile_pathclient_invoice_type_path(三重嵌套)。

请注意,您当前的路由结构(具有两条不同路径的相同资源)可能会使您的控制器逻辑更加复杂。选择一条路线通常就足够了。