可能重复:
为什么我不断收到路由错误?
对不起,我再次问这个问题,但我第一次没有得到任何回应。
我正在尝试向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