簡體   English   中英

無法使用link_to鏈接到正確的路線

[英]Can't link to correct route using link_to

我試圖從我的/clients/:client_id show頁面鏈接到現有路由/clients/:client_id/invoices/:id ,但/clients/:client_id

我有一個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格式,但我一直無法弄清楚。

您使用了錯誤的url_helper和錯誤的參數。 你應該有:

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

要么

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

invoices_path是由resources :invoices (最外面的一個)生成的url_helper,它將把您路由到InvoicesController( /invoices )的索引路徑。 如果您傳遞參數,它將用於格式( /invoices.10非常常見的問題)。

嵌套resources生成的所有路由的名稱均包含這兩種資源,例如new_user_profile_pathclient_invoice_type_path (三重嵌套)。

請注意,您當前的路由結構(具有兩個不同路徑的相同資源)可能會使您的控制器邏輯更加復雜。 通常,只有一條路線,選擇一條就足夠了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM