尝试删除评论时出现500错误。在后端,该注释被删除,但是它会因ActionView :: Template :: Error(对于nil:NilClass的未定义方法“ each”)出错(即使应填充@comments)。我使用window.location.reload(),并且效果很好。有什么办法可以解决这个问题吗?
日志
Started DELETE "/api/comments/51" for ::1 at 2020-07-25 11:48:17 -0400
Processing by Api::CommentsController#destroy as JSON
Parameters: {"id"=>"51"}
Comment Load (0.6ms) SELECT "comments".* FROM "comments" WHERE "comments"."id" = $1 LIMIT $2 [["id", 51], ["LIMIT", 1]]
↳ app/controllers/api/comments_controller.rb:38
(0.2ms) BEGIN
↳ app/controllers/api/comments_controller.rb:39
Comment Destroy (0.8ms) DELETE FROM "comments" WHERE "comments"."id" = $1 [["id", 51]]
↳ app/controllers/api/comments_controller.rb:39
(2.1ms) COMMIT
↳ app/controllers/api/comments_controller.rb:39
Rendering api/comments/index.json.jbuilder
Rendered api/comments/index.json.jbuilder (3.5ms)
Completed 500 Internal Server Error in 21ms (ActiveRecord: 3.7ms)
ActionView::Template::Error (undefined method `each' for nil:NilClass):
1:
2: @comments.each do |comment|
3: json.set! comment.id do
4: json.partial! 'comment', comment: comment
5: end
app/views/api/comments/index.json.jbuilder:2:in `_app_views_api_comments_index_json_jbuilder__2940510328301300636_70181083474860'
app/controllers/api/comments_controller.rb:40:in `destroy'
代表性组件
import React from 'react';
class CommentIndex extends React.Component {
constructor(props) {
super(props)
this.handleDelete = this.handleDelete.bind(this);
}
componentDidMount() {
this.props.fetchComments();
}
componentDidUpdate(prev) {
if (Object.values(prev.comments).length !== Object.values(this.props.comments).length) {
this.props.fetchComments();
}
}
dateCreated(date) {
const dateCreated = new Date(date)
return dateCreated.toLocaleDateString();
}
authorInitial(id) {
const users = Object.values(this.props.state.entities.users);
const user = users.filter(user => user.id === id);
return user[0].username.split("")[0]
}
authorName(id) {
const users = Object.values(this.props.state.entities.users);
const user = users.filter(user => user.id === id);
return user[0].username
}
handleDelete(id) {
this.props.deleteComment(id)
// .then(window.location.reload())
}
render() {
const comments = Object.values(this.props.state.entities.comments);
const videoComments = comments.filter(comment => comment.video_id === this.props.id)
const commentNumber = function () {
if (videoComments.length === 1) {
return "1 Comment"
} else {
return `${videoComments.length} Comments`
}
}
const commentList = videoComments.map(comment => {
return (
<ul key={comment.id} >
<div className="comment-list-item">
<div id="left-side">
<h2 className="comment-author-initial">{this.authorInitial(comment.author_id)}</h2>
<div className="comment-body">
<div className="name-date">
<h2 className="comment-author-name">{this.authorName(comment.author_id)}</h2>
<h2 className="comment-upload-date"> commented on {this.dateCreated(comment.created_at)}</h2>
</div>
<h2 className="comment-text">{comment.body}</h2>
</div>
</div>
{/* {this.props.currentUser.id === comment.author_id ? <button id="delete-button"onClick={() => this.handleDelete(comment.id)}>Edit</button> : null} */}
{this.props.currentUser.id === comment.author_id ? <button id="delete-button"onClick={() => this.handleDelete(comment.id)}>Delete</button> : null}
</div>
</ul>
)
})
return (
<div id="comment-list">
<h1 className="comment-page-title">{commentNumber()}</h1>
<div className="comment-page-container">
<ul id="comment-ul">
<div id="comment-page-list">{commentList}</div>
</ul>
</div>
</div>
)
}
}
export default CommentIndex;
控制器
class Api::CommentsController < ApplicationController
def index
@comments = Comment.all
render :index
end
def new
@comment = Comment.new
render :new
end
def show
@comment = Comment.find(params[:id])
render :show
end
def create
@comment = Comment.new(comment_params)
@comment.author_id = current_user.id
if @comment.save
render :show
else
render json: @comment.errors.full_messages , status: 422
end
end
def update
@comment = Comment.find(params[:id])
if @comment.update(comment_params)
render :show
else
render json: @comment.errors.full_messages, status: 422
end
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
render :index
end
def comment_params
params.require(:comment).permit(:body, :author_id, :video_id)
end
end
答案 0 :(得分:1)
问题的原因很明显:
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
render :index
end
render :index
非常不常规。您可能会成为一个非常常见的误解的受害者-render :index
不会在您的控制器中调用index方法。它只是呈现视图。
在传统的Rails应用中,破坏资源通常会重定向到索引。
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to :index, notice: 'Comment deleted.'
end
如果您要创建一个提供JSON的控制器,则通常只需一个204 - No Content
响应代码即可进行响应:
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
head :no_content
end
但是如果请求正文包含描述状态的JSON之类的实体,您也可以使用200 - OK
进行响应。
通过使用ActionController::MimeResponds,您可以同时进行以下操作:
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
respond_to do |f|
f.html { redirect_to :index }
f.json { head :no_content }
end
end