Rails多态注释ajax - 500(内部服务器错误)

时间:2015-07-08 13:02:01

标签: ruby-on-rails ruby

我使用本教程进行多态注释

https://gorails.com/episodes/comments-with-polymorphic-associations

它运行正常但是当我将远程true设置为我的注释表单时,我在尝试添加新注释时遇到505错误(新注释未附加到列表中)。

但是当我重新加载页面时,新评论会出现在列表中。

这里有什么问题?

我在views / comments文件夹中找到了这些文件:

enter image description here

create.js

<% unless @comment.errors.any? %>
$("ul.comments").append('<%= j render "comments/comment" %>')
$("#new_comment")[0].reset();
<% end %>

_form.html.erb

<%= simple_form_for([commentable, Comment.new], remote: true) do |f| %>
  <%= f.input :body, label: false %>
  <%= f.button :submit, "Submit" %>
<% end %>

comments_controller.rb

  def create
    @comment = @commentable.comments.new(comment_params)
    @comment.user = current_user
    @comment.save
    respond_to do |format|
      format.html { redirect_to @commentable, notice: "Your comment was successfully added."}
      format.js
    end
  end

_comment.html.erb

  <li class="comment">
    <b><%= comment.user.try(:username) %>:</b>
    <%= comment.body%>
  </li>

控制台

enter image description here

UP

我有这条路线

  resources :posts do 
    resources :comments, module: :posts
  end

+ 控制器/帖/ comments_controller

class Posts::CommentsController < CommentsController
  before_action :set_commentable

  private
  def set_commentable
    @commentable = Post.friendly.find(params[:post_id])
  end
end

文件夹结构与此处几乎相同 https://github.com/excid3/gorails-episode-36/tree/master/app/controllers

响应标签显示此

undefined local variable or method `comment' for #<#<Class:0x007f993d3c5450>:0x007f99450a6190>
Trace of template inclusion: app/views/comments/create.js.erb

当我更换

&lt;%= j render @comment%&gt;有一些文字,它会附在提交列表

好的问题是_comment.html erb

1 个答案:

答案 0 :(得分:0)

使用实例变量更新了create.js以进行注释,现在可以正常工作。

<% unless @comment.errors.any? %>
$("ul.comments").append('<%= j render partial: "comments/comment", locals:{comment: @comment} %>')
$("#new_comment")[0].reset();
<% end %>