2014-03-31 26 views
0

当我尝试提交注释时出现错误。 - ActiveRecord的:: RecordNotFound在CommentsController#指数 - 我跟着thisthis教程无法找到没有ID的注释 - 多态关联

的网址是:

.../articles/1/comments 

comments_controller

class CommentsController < ApplicationController 
before_action :set_comment 
before_action :signed_in_user, only: [:new] 

def index 
    @commentable = load_commentable 
    @comments = @commentable.comments 
end 

... 

def create 
    @comment = @commentable.comments.new(comment_params) 
    @comment.user = current_user 

if @comment.save 
    redirect_to @comment, notice: "Comment created." 
else 
    render :new 
end 
end 

.... 

private 

def load_commentable 
    resource, id = request.path.split('/')[1, 2] 
    @commentable = resource.singularize.classify.constantize.find(id) 
end 

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

Full trace:

+0

你可以在问题中分享完整的错误堆栈跟踪,这将有助于调试。 –

+0

我加了全部跟踪 – Absurdim

+0

看到我的回答,并记下'UPDATE'部分。 –

回答

1

按堆栈跟踪,错误出现在set_comment方法中。

您必须在set_comment上有回调before_action这不应该在那里为index操作。您应该仅限于相关操作。

例如:

before_action :set_comment, only: [:show, :edit, :update, :destroy] 

所以这个回调将only被调用为show, edit, update and destroy行动。

UPDATE

目前回调设置为before_action :set_comment没有任何限制,因此将每一个动作之前被调用。所以,按照上面的建议更新它。