ruby-on-rails - ruby 和 rails 中的资源路由

标签 ruby-on-rails ruby routes helper

我有

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#showblogs#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

您使用了没有sresources :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/

相关文章:

c# - ASP MVC 5 和 Web Api 2 无法查看完整链接的页面

ruby-on-rails - 自定义 Rails 脚手架生成器 View 的简单方法?

ruby-on-rails - 如何让 Bootstrap Javascript 在 Ruby on Rails 6 中工作

ruby-on-rails - 使用ruby-thread,sidekiq,并使用Thread.pool与ActiveRecord保存

ruby - 我想建立一个当前月份的日历,并能够浏览过去的月份和 future 的月份

ruby - 为什么 Method#arity 被称为 arity?

ruby-on-rails - 与 Rails 中的资源相比,使用资源有哪些优势?

ruby-on-rails - #<ActionDispatch::Routing::Mapper:0x007fd3b4516a00> 的未定义局部变量或方法 `on'

ruby-on-rails - slim 动态条件类

ruby - 用 minitest 测试鸿沟