找不到没有ID的注释 - 多态关联

时间:2014-03-31 14:43:12

标签: ruby-on-rails ruby-on-rails-4

当我尝试提交评论时出现错误。 - CommentsController #index中的ActiveRecord :: RecordNotFound - 我跟着thisthis教程

网址为:

.../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:

1 个答案:

答案 0 :(得分:1)

根据堆栈跟踪,set_comment方法出现错误。

您必须在before_action上进行回调set_comment,而index行动不应该回复before_action :set_comment, only: [:show, :edit, :update, :destroy] 。您应该将其限制为仅相关的操作。

例如:

only

这样就可以为show, edit, update and destroy操作before_action :set_comment调用此回调。

<强>更新

目前回调设置为{{1}},没有任何限制,因此将在每个操作之前调用它。所以,按照上面的建议更新它。