2015-09-18 23 views
0

我正在使用Ruby on Rails v4,我遇到了一個奇怪的問題,我無法找到原因。我有一個軌道視圖,我試圖做一個簡單的鏈接到記錄。在我看來,我使用Rails link_to創建無效鏈接

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

結果是一個HTML鏈接,看起來像這樣

http://someurl.com/contact.5 

它帶我到我的應用程序的聯繫人頁面,而不是顯示我有一個接觸的5.

ID這是我的簡化的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 

當我使用與上述相同的語法鏈接到客戶時,鏈接工作正常。我搞砸了什麼,爲什麼當鏈接說contact.5時,它給我發送聯繫頁面。

謝謝。

回答

0

這是因爲您已經定義爲提供contact_url幫手路線:

get 'contact' => 'static_pages#contact' 

這意味着您可以使用contact_urlcontact_path以獲取到您的靜態聯繫頁面的路由。

當rails試圖鏈接到一個對象時,它使用該對象類型的url helper方法。因此,當您執行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 
+0

感謝@Shadwell。我注意到,當我運行耙路線時,客戶和聯繫人不同,但我無法弄清楚原因。也感謝向我展示如何改變它。我是新手,這對我很有幫助。 – mack

0

在route.rb行給出了這樣的衝突:

get 'contact' => 'static_pages#contact'