Rails "No route matches" 错误

Rails "No route matches" error

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

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

以下是 link 编辑客户详细信息的工作视图行(客户有很多工作,但没有嵌套资源):

<%= 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 routes 给出以下内容:

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

因此您始终知道 ID 的外观。 (要使这项工作一直通过资源进行,需要一些技巧)。

另外,另一个潜在的问题(这让我抓狂了几次)是我在同一页面上实例化了一个空白实例,该实例是我试图路由到的 class。例如@customer = Customer.new,link 正在查找,但由于记录尚未保存而未找到 ID。

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

在你的情况下,它的意思是这样的。

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