繁体   English   中英

评论删除 ActionView::Template::Error (nil:NilClass 的未定义方法 `each'):

[英]Comment delete ActionView::Template::Error (undefined method `each' for nil:NilClass):

尝试删除评论时出现 500 错误。 在后端,评论被删除,但它会因 ActionView::Template::Error (undefined method `each' for nil:NilClass) 出错:即使应该填充 @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;

controller

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

问题的原因是不言而喻的:

def destroy
  @comment = Comment.find(params[:id])
  @comment.destroy
  render :index
end

render:index是非常规的。 您可能会成为一个非常常见的误解的受害者——render render:index不会调用 controller 中的 index 方法。 它只是渲染视图。

在经典的 Rails 应用程序中,销毁资源通常会重定向到索引。

def destroy
  @comment = Comment.find(params[:id])
  @comment.destroy
  redirect_to :index, notice: 'Comment deleted.'
end

如果您正在创建一个为 JSON 服务的 controller,您通常会使用204 - No Content响应代码进行响应:

def destroy
  @comment = Comment.find(params[:id])
  @comment.destroy
  head :no_content
end

但是您也可以用200 - OK来响应,如果请求正文包含一个描述状态的实体,例如一些 JSON。

通过使用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

ActionView::Template::Error (#&lt;# 的未定义局部变量或方法“事件” <class::0x000.. rails 6 ajax< div><div id="text_translate"><p> 我建立了一个表格,允许您内联编辑记录; 我遇到的问题是部分数据在视图中刷新后不会重新渲染数据。 我正在使用单独的 controller 来处理更新/编辑部分渲染。 我可以成功地内联呈现表单,我只是无法通过更新部分错误而没有收到未定义的局部变量。 如何在不同的 controller 中重新渲染我的 update.js.erb 操作的部分?</p><p> <strong>图表/facility_chart.html.erb</strong></p><pre> &lt;div class="divTable greyGridTable"&gt; &lt;div class="divTableHeading"&gt; &lt;div class="divTableRow"&gt; &lt;div class="divTableHead"&gt;Date&lt;/div&gt; &lt;% @facility_chart_events.select(:name).distinct.each |event_name| %&gt; &lt;div class="divTableHead"&gt;&lt;%= event_name %&gt;&lt;/div&gt; &lt;% end %&gt; &lt;div class="divTableHead"&gt;Update/Change&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="divTableBody"&gt; &lt;% @facility_event_grids.each do |event| %&gt; &lt;%= content_tag:div, class: 'divTableRow', id: dom_id(event) do %&gt; &lt;%= render partial: "facility_event_trackers/facility_event_tracker", :locals =&gt; {event: event} %&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;/div&gt; &lt;/div&gt;</pre><p> <strong>_inline_form.html.erb</strong></p><pre> &lt;%= form_with model: facility_event_tracker, class: 'divTableRow', id: dom_id(facility_event_tracker, 'inline_form'), local: false do |f| %&gt; &lt;div class="divTableCell"&gt; &lt;%= chart_tracker_grid_date(f.object.start_time) %&gt; &lt;/div&gt; &lt;div class="divTableCell"&gt; &lt;%= text_field:event_count, label: false %&gt; &lt;/div&gt; &lt;% end %&gt; &lt;div class="divTableCell"&gt; &lt;%= f.submit 'Submit', class: 'ui black button basic' %&gt; &lt;/div&gt;</pre><p> <strong>图表控制器.rb</strong></p><pre> def facility_chart @facility = Facility.find(params[:id]) @facility_events_grids = @facility.facility_event_trackers.order(start_time: :desc).page(params[:page]).per(40) end</pre><p> <strong>facility_event_trackers_controller.rb</strong></p><pre> def edit end def update respond_to do |format| if @facility_event_tracker.update(facility_event_tracker_params) format.js {} else format.js {} end</pre><p> <strong>编辑.js.erb</strong></p><pre> document.getElementById('&lt;%= dom_id(@facility_event_tracker) %&gt;').insertAdjacentHTML('afterend', "&lt;%= j render 'inline_form', facility_event_tracker: @facility_event_tracker %&gt;");</pre><p> <strong>更新.js.erb</strong></p><pre> document.getElementById('&lt;%= dom_id(@facility_event_tracker, 'inline_form') %&gt;').remove() document.getElementById('&lt;%= dom_id(@facility_event_tracker, 'inline_form') %&gt;').innerHTML = &lt;%= j render "facility_event_trackers/facility_event_tracker", facility_event_tracker: @facility_event_tracker %&gt;" document.getElementById('&lt;%= dom_id(@facility_event_tracker) %&gt;').style.display = 'table-row'</pre><p> <strong>Rails 控制台错误</strong></p><p> // 部分无法重新渲染以进行更新</p><pre>ActionView::Tempalate::Error (undefined local variable or method `event' for #&lt;#&lt;Class:0x00000&gt;:0x00005&gt;): 1: &lt;div class="divTableCell"&gt;&lt;%= chart_tracker_grid_date(event.start_time) %&gt;... 2: &lt;div class="divTableCell"&gt;&lt;%= event.event_count %&gt;&lt;/div&gt; app/views/facility_event_trackers/_facility_event_tracker.html.erb:1 app/views/facility_event_trackers/update.js.erb</pre></div></class::0x000..>

[英]ActionView::Template::Error (undefined local variable or method `event' for #<#<Class::0x000.. Rails 6 AJAX

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HTTP500:服务器错误! ActionView :: Template :: Error(nil:NilClass的未定义方法“ id”) Rails为nil:NilClass创建动作未定义的方法“ each” nil:NilClass的未定义方法“事件” 未定义的方法“公司”为 nil:NilClass nil:NilClass rails 4的未定义方法`category` EasyMarklet Rails gem:nil:NilClass的未定义方法“ []” Ruby on rails,ajax,offset,limit。 nil:NilClass的未定义方法“ each” ActionView::Template::Error (#&lt;# 的未定义局部变量或方法“事件” <class::0x000.. rails 6 ajax< div><div id="text_translate"><p> 我建立了一个表格,允许您内联编辑记录; 我遇到的问题是部分数据在视图中刷新后不会重新渲染数据。 我正在使用单独的 controller 来处理更新/编辑部分渲染。 我可以成功地内联呈现表单,我只是无法通过更新部分错误而没有收到未定义的局部变量。 如何在不同的 controller 中重新渲染我的 update.js.erb 操作的部分?</p><p> <strong>图表/facility_chart.html.erb</strong></p><pre> &lt;div class="divTable greyGridTable"&gt; &lt;div class="divTableHeading"&gt; &lt;div class="divTableRow"&gt; &lt;div class="divTableHead"&gt;Date&lt;/div&gt; &lt;% @facility_chart_events.select(:name).distinct.each |event_name| %&gt; &lt;div class="divTableHead"&gt;&lt;%= event_name %&gt;&lt;/div&gt; &lt;% end %&gt; &lt;div class="divTableHead"&gt;Update/Change&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="divTableBody"&gt; &lt;% @facility_event_grids.each do |event| %&gt; &lt;%= content_tag:div, class: 'divTableRow', id: dom_id(event) do %&gt; &lt;%= render partial: "facility_event_trackers/facility_event_tracker", :locals =&gt; {event: event} %&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;/div&gt; &lt;/div&gt;</pre><p> <strong>_inline_form.html.erb</strong></p><pre> &lt;%= form_with model: facility_event_tracker, class: 'divTableRow', id: dom_id(facility_event_tracker, 'inline_form'), local: false do |f| %&gt; &lt;div class="divTableCell"&gt; &lt;%= chart_tracker_grid_date(f.object.start_time) %&gt; &lt;/div&gt; &lt;div class="divTableCell"&gt; &lt;%= text_field:event_count, label: false %&gt; &lt;/div&gt; &lt;% end %&gt; &lt;div class="divTableCell"&gt; &lt;%= f.submit 'Submit', class: 'ui black button basic' %&gt; &lt;/div&gt;</pre><p> <strong>图表控制器.rb</strong></p><pre> def facility_chart @facility = Facility.find(params[:id]) @facility_events_grids = @facility.facility_event_trackers.order(start_time: :desc).page(params[:page]).per(40) end</pre><p> <strong>facility_event_trackers_controller.rb</strong></p><pre> def edit end def update respond_to do |format| if @facility_event_tracker.update(facility_event_tracker_params) format.js {} else format.js {} end</pre><p> <strong>编辑.js.erb</strong></p><pre> document.getElementById('&lt;%= dom_id(@facility_event_tracker) %&gt;').insertAdjacentHTML('afterend', "&lt;%= j render 'inline_form', facility_event_tracker: @facility_event_tracker %&gt;");</pre><p> <strong>更新.js.erb</strong></p><pre> document.getElementById('&lt;%= dom_id(@facility_event_tracker, 'inline_form') %&gt;').remove() document.getElementById('&lt;%= dom_id(@facility_event_tracker, 'inline_form') %&gt;').innerHTML = &lt;%= j render "facility_event_trackers/facility_event_tracker", facility_event_tracker: @facility_event_tracker %&gt;" document.getElementById('&lt;%= dom_id(@facility_event_tracker) %&gt;').style.display = 'table-row'</pre><p> <strong>Rails 控制台错误</strong></p><p> // 部分无法重新渲染以进行更新</p><pre>ActionView::Tempalate::Error (undefined local variable or method `event' for #&lt;#&lt;Class:0x00000&gt;:0x00005&gt;): 1: &lt;div class="divTableCell"&gt;&lt;%= chart_tracker_grid_date(event.start_time) %&gt;... 2: &lt;div class="divTableCell"&gt;&lt;%= event.event_count %&gt;&lt;/div&gt; app/views/facility_event_trackers/_facility_event_tracker.html.erb:1 app/views/facility_event_trackers/update.js.erb</pre></div></class::0x000..> Rails Carrierwave为nil:NilClass上传多个文件未定义的方法[[]] 如何解决“ NoMethodError(nil:NilClass的未定义方法[]”):应用程序/控制器/…”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM