簡體   English   中英

導軌5未定義模板錯誤

[英]rails 5 undefine template error

我正在創建rails 5並向以模態顯示的show action添加注釋

在我的表演動作中發表評論,我有這樣的感覺

    @selfie = Selfy.find(params[:id])
    respond_to do |format|
        format.js
    end

我不能通過這樣的模態來展示

<%= link_to fetch_selfy_path(selfie.id), class: "show_lightbox", data: { featherlight: "mylightbox" }, remote: true do %>

      <img class="card-main-image" src="<%= selfie.photo.url if selfie.photo.url  %>" alt="Image Alt text">
    <% end %>
<div class="lightbox" id="lightbox">
    <%=render partial: "selfies/show", locals: { selfie: selfie }  %>
</div>

單擊按鈕后,我們將顯示操作和注釋

  <% selfie.comments.each do |comment| %>
              <%= render partial: "selfies/comments/comment",  locals: { comment: comment } %>
            <% end %>

局部看起來像

  <p> <b><%= comment.user.username %>: </b><%= comment.body %></p>

在我嘗試通過ajax注入新的commect之前,所有這些方法都可以正常工作

addCommentToSelfie("<%= j render "selfies/comments/comment", locals: { comment: @comment } %>");

這返回和錯誤

ActionView::Template::Error (undefined local variable or method `comment' for #<#<Class:0x007f207400c648>:0x00557937265830>):
    1: 
    2:   <p> <b><%= comment.user.username %>: </b><%= comment.body %></p>

app/views/selfies/comments/_comment.html.erb:2:in `_app_views_selfies_comments__comment_html_erb__4557429192479440105_46989553619000'

我嘗試了不同的方法,但仍然收到相同的錯誤

您正在混合使用不同的語法和一些引號。 如果您使用locals: ...還必須使用partial: :,或者在這種情況下都省略兩者...

addCommentToSelfie("<%= j render 'selfies/comments/comment', comment: @comment %>");

根據以上提供的答案,我能夠解決我的問題

首先,我將creat.js.erb清理為

$("#comments").append("<%= j render partial:  'selfies/comments/comment', locals: { comment: @comment } %>");

secondy正在獲取錯誤nil類,因為我沒有在我的注釋控制器中使用即時變量

從:

def create
  comment =  @selfie.comments.new(comment_params)
  comment.user = current_user
  comment.save

  end

至:

def create
  @comment =  @selfie.comments.new(comment_params)
  @comment.user = current_user
  @comment.save
  respond_to do |format|
      format.js
  end

從那里一切順利

您能告訴我們在評論控制器中創建的操作嗎? 通常,我會做類似的事情。

  def create
    @comment = @selfie.comments.new(comment_params)
    @comment.user = current_user
    respond_to do |format|
      if @comment.save
        format.html { redirect_to @comment }
        format.js
      else
        render :new
      end
    end
  end

然后在您的視圖中,您應該擁有包含您的js的文件comment / create.js.erb:

addCommentToSelfie("<%= j render 'selfies/comments/comment', comment: @comment %>");

現在@comment應該存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM