簡體   English   中英

Rails路由問題,無法找出鏈接路徑

[英]Rails routing issue, can't figure out the link path

讓我從一開始就公平,並告訴您我已經“解決”了我描述的問題。 但是您不了解的解決方案並不是真正的解決方案,是嗎?

我有資源,新聞快訊。 我有一個Newsbites的索引頁。 我所有的CRUD動作均正常。

我創建了一個單獨的索引( frontindex.html.erb ),用作我網站的首頁,以顯示最新的新聞快訊。 格式與我的常規索引不同,因此讀者可以獲得更大的照片,更多的文章文字(也包括更多廣告:)。

在我的路由表中,我有以下語句:

 resources :newsbites
 get 'newsbites/frontindex'
 root 'newsbites#frontindex'

耙路顯示以下內容:

newsbites_frontindex GET    /newsbites/frontindex(.:format)   newsbites#frontindex

如果我從根目錄(localhost:3000)加載網站,則效果很好。 頂部呈現了一個單獨的菜單頁面,並且可以正常加載。 我可以單擊除“ Home ”鏈接以外的所有鏈接,它們可以正常工作。

“主頁”鏈接為:

 <%= link_to 'Home', newsbites_frontindex_path %>

當我單擊鏈接時,出現以下錯誤:

Couldn't find Newsbite with 'id'=frontindex

錯誤指向我的Newbites控制器的' show '操作。 這是frontindex並顯示控制器的def。 它們的顯示方式與我發布它們的方式完全相同:

  def frontindex
  @newsbites = Newsbite.all
  end


  def show
   @newsbite = Newsbite.find(params[:id])
  end

我不明白 當同時具有def和視圖時,為什么newbites_frontindex_path調用show動作? 現在,我可以通過簡單地指向root_path來解決此問題。 但這並不能幫助我理解。 如果這不是網站的根目錄怎么辦?

任何幫助將不勝感激。

實際上,我很驚訝您的代碼完全奏效。 一條路線必須定義兩件事

  • 某種正則表達式的針對該用戶的URL匹配( newsbites/frontindex比不同newsbites/backindex
  • 您要為給定的URL做些什么? 您要指向控制器動作

Rails通常不會“猜測”該動作是什么。 或者,也許他仍然能夠“猜測”您想使用newsbites控制器,但是這次沒有猜測到正確的動作:(。

您應該這樣聲明根,這就是您所做的

root 'controller#action'

對於其余部分,有兩種聲明方法。 我喜歡第二個

resources :newsbites
get 'newsbites/frontindex', to: 'newsbites#frontindex'

resources :newsbites do
  # stuff added here will have the context of the `newsbites` controller already
  get 'frontindex', on: :collection # the name of the action is inferred to be `frontindex`
end

on: :collection表示'frontindex'是涉及所有新聞比特的動作,因此生成的URL將是newsbites/frontindex

另一方面get 'custom_action', on: :member意味着該newsbites/:id/custom_action以特定項目為目標,生成的URL看起來像newsbites/:id/custom_action

編輯 :Rails還基於路線聲明生成path_helpers

get 'test', to: 'newsbites#frontindex'
get 'test/something', to: 'newsbites#frontindex'
resources :newsbites do
      get 'frontindex', on: :collection
      get 'custom_action', on: :member

將生成路徑助手

test_path
test_something_path
# CRUD helpers : new/edit/show/delete, etc. helpers
frontindex_newsbites_path
custom_actions_newsbite_path(ID) # without s !

您始終可以通過添加as:選項來覆蓋它

get 'custom_action', on: :member, as: 'something_cool'
# => something_cool_newsbites_path

Rails路線認為frontindex是一個id。 這就是錯誤消息的內容。 所以,去GET newsbite/:id映射到show

您需要找到一種使Rails路由知道frontindex不是id

附帶說明:定義路線的順序很重要。 將使用第一個匹配的內容。 如果您具有GET newsbite/:idGET newsbite/frontindex ,則將首先出現的那個匹配。 在您的情況下,這是第一個。 也許嘗試更改順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM