簡體   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