Reputation: 233
The error appears when I try to submit a comment. - ActiveRecord::RecordNotFound in CommentsController#index - I followed this and this tutorial
the URL is:
.../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
....
Upvotes: 0
Views: 201
Reputation: 53048
As per the stacktrace, error is appearing on set_comment
method.
You must be having a callback before_action
on set_comment
which should not be there for index
action. You should restrict that to only relevant actions.
For example:
before_action :set_comment, only: [:show, :edit, :update, :destroy]
So that this callback would only
be invoked for show, edit, update and destroy
actions.
UPDATE
Currently callback is set as before_action :set_comment
without any restrictions so it will be invoked before each and every action. So, update it as suggested above.
Upvotes: 1