没有路线匹配{:action =>" show" ....:controller ="帖子" }

时间:2017-04-07 09:39:38

标签: ruby-on-rails

我正在关注article来测试站点地图生成。这篇文章没有提到有关撰写show行动的任何内容。但是自从我开始出现这个错误后,我甚至写了一个简单的show动作。以下是我的帖子控制器:

def index
  @posts= Post.all
end

def show
 @posts = Post.all
end

的routes.rb

Rails.application.routes.draw do
    resources :categories do
      resources :posts
    end
    root to: 'pages#index'
end

sitemap.rb

 Category.find_each do |category|
    add category_posts_path(category), :changefreq => 'weekly', :lastmod => category.updated_at

    category.posts.each do |post|
      add category_post_path(category), :changefreq => 'yearly', :lastmod => post.updated_at
    end
  end

当我运行rake sitemap:refresh时,它会给出以下内容:

In '/home/mypc/Projects/sitemaptest/public/':
rake aborted!
ActionController::UrlGenerationError: No route matches {:action=>"show", :category_id=>#<Category id: 1, title: "Surprised by Joy", created_at: "2017-04-07 09:13:52", updated_at: "2017-04-07 09:13:52">, :controller=>"posts"} missing required keys: [:id]

2 个答案:

答案 0 :(得分:2)

我认为你错过了post param:

category.posts.each do |post|
  add category_post_path(category), :changefreq => 'yearly', :lastmod => post.updated_at
end

应该是:

 category.posts.each do |post|
   add category_post_path(category, post), :changefreq => 'yearly', :lastmod => post.updated_at
 end

希望它有所帮助。

答案 1 :(得分:1)

你应该这样使用:

 Category.find_each do |category|
    add category_posts_path(category), :changefreq => 'weekly', :lastmod => category.updated_at

    category.posts.each do |post|
      add category_post_path(category, post), :changefreq => 'yearly', :lastmod => post.updated_at
    end
  end

您丢失了帖子对象,并且nested路由就是missing required keys: [:id]问题的原因。