导轨"No route matches"错误



我的Rails应用程序中出现以下错误:

没有路由匹配{:action=>"edit",:controller=>"customers",:customer_id=>1}

以下是要链接以编辑客户详细信息的作业视图行(客户有许多作业,但没有嵌套的资源):

<%= link_to job.customer_id, edit_customer_path(:customer_id => job.customer_id) %>

以下是控制器中的编辑定义:

def edit
  if params[:customer_id]
    @customer = Customer.find(params[:customer_id])   
  elsif params[:id]
    @customer = Customer.find(params[:id])
  end
  respond_to do |format|
    format.html # edit.html.erb
    format.json { render json: @customer }
  end
end

rake路由提供以下内容:

edit_customer GET    /customers/:id/edit(.:format) customers#edit

注:

如果我将视图更改为:

<%= link_to job.customer_id, edit_customer_path(:id => job.customer_id) %>

然后我得到了相同的错误,但带有":id=nil"(即根本没有传递值):

No route matches {:action=>"edit", :controller=>"customers", :id=>nil}

我对此有点陌生,但有人能解释一下发生了什么吗?

谢谢!

更新

试着这样写你的路径

edit_customer_path(job.customer) if job.customer

在路线中,为客户指定一个参数。

resources :customers, param: :customer_id

所以你总是知道身份证会是什么样子。(需要一些技巧才能通过资源实现这一点)。

此外,另一个潜在的问题(这让我有几次陷入困境)是,我在同一页上实例化了我试图路由到的同一类的一个空白实例。例如@customer=customer.new,链接正在查找它,但由于记录尚未保存,找不到id。

我发现命名路由很麻烦,更喜欢使用多态url,因为它们会优雅地降级。

在你的情况下,这意味着这样的事情。

link_to 'whev', [:edit, @customer]

相关内容

最新更新