【问题标题】:Resource route in ruby and railsruby 和 rails 中的资源路由
【发布时间】:2014-03-05 16:55:11
【问题描述】:

我有

resources :blog

在我的routes.rb 文件中声明,但是当我尝试在控制器或html.erb 文件中访问blog_path 时,我收到以下错误:

No route matches {:controller=>"blog", :action=>"show"} missing required keys: [:id]

我创建了一个名为BlogController 的控制器,并在views 目录中使用show.html.erb 文件定义了方法show。如果我定义:

match '/blog', to: 'blog#show', via: 'get',然后blog_path 工作正常。

我的理解是资源:blog 只是match '/blog', to: 'blog#show', via: 'get' 和一堆其他路线的语法糖。请帮忙。

【问题讨论】:

    标签: ruby-on-rails ruby routes helper


    【解决方案1】:

    blog_path 用于生成博客路径,因此您需要id 或博客对象,此助手生成路径如/blogs/12blogs#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
    

    您使用了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
    

    【讨论】:

    • 这是否意味着所有资源都必须以's'结尾?喜欢资源:照片,资源:博客
    【解决方案2】:

    像这样使资源复数 资源:博客

    并使控制器名 blogs_controller.rb 及其类名 BlogsController

    这是轨道标准

    【讨论】:

      【解决方案3】:

      我最近开始使用 Rails,但我注意到当 Rails 为我生成控制器时,它在名称和单词控制器之间使用下划线命名它。

      类似“blog_controller.rb”的东西,几天前我将一个替换为另一个没有下划线并得到类似的错误,不知道为什么。

      也许对你有帮助。

      您好!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-12
        • 2013-02-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多