Rails link_to 创建无效链接

Rails link_to Creating Invalid Links

我在 Rails v4 上使用 Ruby,我遇到了一个奇怪的问题,我无法找到原因。我有一个 rails 视图,我试图在其中对记录进行简单的 link 处理。在我看来,我正在使用

<%= link_to contact.first_name + " " + contact.last_name, contact %>

结果是 html link 看起来像这样

http://someurl.com/contact.5

这会将我带到应用程序的联系人页面,而不是显示 ID 为 5 的联系人。

这是我简化后的 routes.rb 的样子

Rails.application.routes.draw do

  root                'dashboard#index'
  get    'help'    => 'static_pages#help'
  get    'about'   => 'static_pages#about'
  get    'contact' => 'static_pages#contact'

  resources :customers
  resources :contacts

end

这些是我的路线:

       root GET    /                                       dashboard#index
       help GET    /help(.:format)                         static_pages#help
      about GET    /about(.:format)                        static_pages#about
    contact GET    /contact(.:format)                      static_pages#contact
  customers GET    /customers(.:format)                    customers#index
            POST   /customers(.:format)                    customers#create
new_customer GET    /customers/new(.:format)                customers#new
edit_customer GET    /customers/:id/edit(.:format)           customers#edit
   customer GET    /customers/:id(.:format)                customers#show
            PATCH  /customers/:id(.:format)                customers#update
            PUT    /customers/:id(.:format)                customers#update
            DELETE /customers/:id(.:format)                customers#destroy
   contacts GET    /contacts(.:format)                     contacts#index
            POST   /contacts(.:format)                     contacts#create
new_contact GET    /contacts/new(.:format)                 contacts#new
edit_contact GET    /contacts/:id/edit(.:format)            contacts#edit
            GET    /contacts/:id(.:format)                 contacts#show
            PATCH  /contacts/:id(.:format)                 contacts#update
            PUT    /contacts/:id(.:format)                 contacts#update
            DELETE /contacts/:id(.:format)                 contacts#destroy

当我对客户使用与上述相同的语法 link 时,link 工作正常。我搞砸了什么,为什么当 link 说 contact.5 时它会向我发送联系页面?

谢谢。

您的 route.rb 中的行给出了此冲突:

get    'contact' => 'static_pages#contact'

这是因为您已经定义了一个提供 contact_url 助手的路由:

get    'contact' => 'static_pages#contact'

这意味着您可以使用 contact_urlcontact_path 获取静态联系页面的路由。

当 rails 尝试 link 一个对象时,它使用该对象类型的 url 辅助方法。因此,当您执行 link_to(..., contact) 时,它会使用现有的 contact_url 方法来生成路线。

您也可以在 rake routes 输出中看到差异(在客户和联系人之间)。对于客户,您会得到 #show 操作行的不同输出:

customer GET    /customers/:id(.:format)                customers#show

对于 contact 但丢失的联系人:

         GET    /contacts/:id(.:format)                 contacts#show

因为已经定义了 contact 路由。

您可以通过为静态联系路由定义不同的名称来解决这个问题:

get 'contact', to: 'static_pages#contact', as: :static_contact