[英]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.