无法使用link_to链接到正确的路由

时间:2016-03-10 02:44:22

标签: ruby-on-rails has-many-through link-to

我正在尝试链接到现有路线/clients/:client_id 来自我的show 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 我尝试了一些不同的{{1}}格式,但我无法弄明白。

1 个答案:

答案 0 :(得分:2)

你使用了错误的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(三重嵌套)。

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