0

可能重复:
为什么我不断收到路由错误?

对不起,我再次问这个问题,但我第一次没有得到任何回应。

我正在尝试向michael hartl railstutorial的https://github.com/railstutorial/sample_app_2nd_ed中的微博添加评论

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

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

这是我尝试访问用户页面时遇到的错误:No route matches {: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
4

1 回答 1

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_idurl——您要添加评论的微博的 ID 号在哪里。

您能否确认您发布到的网址以及您希望它能做什么?

于 2012-05-19T03:20:54.970 回答