2014-02-08 65 views
1

資源路線和軌道

資源:博客

在我的routes.rb文件中聲明,但是當我嘗試在一個控制器或html.erb文件訪問blog_path,我得到以下錯誤:

沒有路由匹配{:控制器=> 「博客」,:動作=> 「節目」}缺少必需的鍵:[:ID]

我已經創建了一個稱爲BlogController控制器和帶有所定義的方法顯示views目錄中的show.html.erb文件。如果我定義:

match'/ blog',to:'blog#show',via:'get'instead,then blog_path works fine。

我的理解是資源:博客只是匹配'/ blog'的語法糖,'blog'show',via:'get'和一堆其他路線。請幫忙。

回答

6

blog_path是用於產生到博客路徑,所以需要id或博客對象,這個輔助產生像/blogs/12路徑blogs#show,並blogs#show是用於示出對象。 blogs_path生成/blogsblogs#index(喜歡到所有博客)。

2 Resource Routing: the Rails Default

resources :photos 

GET  /photos   index display a list of all photos 
GET  /photos/new  new  return an HTML form for creating a new photo 
POST  /photos   create create a new photo 
GET  /photos/:id  show  display a specific photo 
GET  /photos/:id/edit edit  return an HTML form for editing a photo 
PATCH/PUT /photos/:id  update update a specific photo 
DELETE  /photos/:id  destroy delete a specific photo 

您已經使用resources :blog沒有s。它產生

  blog_index GET /blog(.:format)           blog#index 
         POST /blog(.:format)           blog#create 
       new_blog GET /blog/new(.:format)          blog#new 
      edit_blog GET /blog/:id/edit(.:format)         blog#edit 
        blog GET /blog/:id(.:format)          blog#show 
         PUT /blog/:id(.:format)          blog#update 
         DELETE /blog/:id(.:format)          blog#destroy 
+0

這是否意味着所有資源必須以結束's' 嗎?喜歡的資源:照片,資源:博客 – stephen

+0

謝謝,它現在非常清楚,這是公認的答案。 – stephen

0

我最近我開始使用Rails的,但我注意到,當Rails的我產生控制器,它的名字與它的名字和字控制器之間的下劃線。

類似於「blog_controller.rb」,幾天前我將其中一個替換爲沒有下劃線的其他人,並得到類似的錯誤,而不是爲什麼。

也許它可以幫助你。

問候!

3

進行資源複數這樣 資源:博客

而且使控制器名稱blogs_controller.rb和它的類名BlogsController

這是鐵軌標準