运行我的Rails应用程序时,为什么一直出现路由错误?

时间:2012-05-19 02:54:59

标签: ruby-on-rails

  

可能重复:
  Why do I keep getting a routing error?

很抱歉我再次问这个,但我第一次没有收到任何回复。

我正在尝试为michael hartl railstutorial中的https://github.com/railstutorial/sample_app_2nd_ed中的微博添加注释

以下是我的routes.rb文件中的相关区域。

resources :microposts, only: [:create, :destroy] do
    resources :comments, 
  end

这是我尝试访问用户页面时遇到的错误:没有路由匹配{:controller =>“comments”,:format => nil,:micropost_id =>#}

这里是rake路径的输出grep评论:

         user_comments GET    /users/:user_id/comments(.:format)                    comments#index
                       POST   /users/:user_id/comments(.:format)                    comments#create
      new_user_comment GET    /users/:user_id/comments/new(.:format)                comments#new
     edit_user_comment GET    /users/:user_id/comments/:id/edit(.:format)           comments#edit
          user_comment GET    /users/:user_id/comments/:id(.:format)                comments#show
                       PUT    /users/:user_id/comments/:id(.:format)                comments#update
                       DELETE /users/:user_id/comments/:id(.:format)                comments#destroy
    micropost_comments GET    /microposts/:micropost_id/comments(.:format)          comments#index
                       POST   /microposts/:micropost_id/comments(.:format)          comments#create
 new_micropost_comment GET    /microposts/:micropost_id/comments/new(.:format)      comments#new
edit_micropost_comment GET    /microposts/:micropost_id/comments/:id/edit(.:format) comments#edit
     micropost_comment GET    /microposts/:micropost_id/comments/:id(.:format)      comments#show
                       PUT    /microposts/:micropost_id/comments/:id(.:format)      comments#update
                       DELETE /microposts/:micropost_id/comments/:id(.:format)      comments#destroy

最后这是我的comments_controller.rb

class CommentsController < ApplicationController 
  def create
    @micropost = Micropost.find(params[:micropost_id]) 
    @comment = @micropost.comments.build(params[:comment]) 
    @comment.user = current_user

    if @comment.save 
      redirect_to @micropost
    else 
      redirect_to @micropost
    end 
  end 

  def show
    @comment = Comment.find(params[:id])
  end

  def new 

  end

  def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy
    redirect_back_or root_path
  end
end

1 个答案:

答案 0 :(得分:1)

您的路由代码生成的路由是:

GET    /microposts/:micropost_id/comments
POST   /microposts/:micropost_id/comments
GET    /microposts/:micropost_id/comments/new
GET    /microposts/:micropost_id/comments/:id/edit
GET    /microposts/:micropost_id/comments/:id
PUT    /microposts/:micropost_id/comments/:id
DELETE /microposts/:micropost_id/comments/:id
POST   /microposts
DELETE /microposts/:id

因此,要访问您的评论控制器,您需要从表单发布到网址/microposts/:micropost_id/comments - 其中:micropost_id是您要添加评论的微博的ID号。< / p>

你能否确认你要发布的网址以及你希望它会做什么?