我有
resources :blog
在我的 routes.rb
文件中声明,但是当我尝试访问 Controller 或 html.erb
文件中的 blog_path
时,我得到以下错误:
No route matches {:controller=>"blog", :action=>"show"} missing required keys: [:id]
我创建了一个名为 BlogController
的 Controller ,并在 views 目录中使用 show.html.erb
文件定义了方法 show
。如果我定义:
将 '/blog' 匹配到:'blog#show',改为通过:'get'
,然后 blog_path
工作正常。
我的理解是资源:blog
只是 match '/blog', to: 'blog#show', via: 'get'
和一堆语法糖其他路线。请帮忙。
最佳答案
blog_path
用于生成博客路径,因此您需要 id
或博客对象,此助手生成类似 /blogs/12
的路径> 到 blogs#show
,blogs#show
用于显示一个对象。 blogs_path
生成 /blogs
到 blogs#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
您使用了没有s
的resources :blog
。它产生
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
关于ruby-on-rails - ruby 和 rails 中的资源路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641981/