【问题标题】:rails routes error in the Official Guide官方指南中的 rails routes 错误
【发布时间】:2016-09-09 10:56:38
【问题描述】:

我是 ROR 的新手,我正在阅读 Ruby on Rails 官方指南 (4.2.6),但是当我想添加 Article 模型时遇到了一个问题。

当我尝试保存文章时出现错误,

undefined method `article_url' for # 你的意思是?文章网址

我发现路由中没有“article”前缀:

majiandeMacBook-Pro:blog majian$ bin/rake routes 在进程 26766 中通过 Spring 预加载器运行 前缀动词 URI 模式控制器#Action welcome_index GET /welcome/index(.:format) 欢迎#index 根 GET / 欢迎#index 文章 POST /articles(.:format) 文章#create new_articles GET /articles/new(.:format) 文章#new edit_articles GET /articles/edit(.:format) 文章#edit 获取 /articles(.:format) 文章#show PATCH /articles(.:format) 文章#update PUT /articles(.:format) 文章#update 删除 /articles(.:format) 文章#destroy

但是在文档中,我发现应该是这样的:

文章 GET /articles/:id(.:format) 文章#show

有人知道为什么路线不同吗?任何帮助将不胜感激。

【问题讨论】:

标签: ruby-on-rails


【解决方案1】:

检查您的 routes.rb 文件,它应该如下所示:

文件在config/routes.rb中

Rails.application.routes.draw do
  get 'welcome/index'
  resources :articles
  root 'welcome#index'

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

错误可能是由“resources :articles”行中的错误引起的

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,这是因为我在routes.rb 中拼错了resources :article 我有resource :article,但那不起作用

    【讨论】:

      【解决方案3】:

      article_url 需要文章的 id 作为参数,在你的show 操作中你应该有这样的东西

      article_url(@article)
      

      【讨论】:

      • 没有article(单数)路由,所以这行不通。我相信 OP 使用想要使用单数 (article) 而不是复数 (articles)。所以这是resourceresources 的问题。
      • 你说得对,可能他的routes.rb有问题
      • 我在 routes.rb 中发现了错误。我设置了“resources:articles”而不是“resources:articles”,我什至不知道我拼写错误时它可以工作。
      猜你喜欢
      • 2018-06-11
      • 2014-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      相关资源
      最近更新 更多