Rails 多态注释

Rails polymorhic comments

我正在构建一个 reddit 克隆(只是为了练习))并且对新评论回复的表单有问题。我使用 this 教程来构建多态评论并且一切正常,但我想在回复下方添加新评论回复的表单,以便您单击 link 并出现表单(div 的形式默认隐藏)。但似乎我在表单中生成的每个新对象都会出现该表单,所以这只是无限循环。有什么方法可以创建评论回复表单吗?

这是我的 _form:

  = form_for comment do |f|
    p
      = f.label :body
      = f.text_area :body

      = f.hidden_field :link_id, value: params[:link_id]

      - if params[:link_id]
        = hidden_field_tag :link_id, params[:link_id]
      - if params[:comment_id]
        = hidden_field_tag :comment_id, params[:comment_id]

    = f.submit "Create", class: "button tiny"

和_comment部分:

li.comment
  p = comment.body

  p = link_to "Add a reply", "", class: "reply_link"
  .comment_form
    = render 'comments/form', comment: comment.comments.build

  - unless comment.comments.empty?
    ul.comments_list
      = render partial: 'comments/comment', collection: comment.comments

我通过以下 jQuery 解决了这个问题。

$(document).ready(function() {
    $('.partner-area').click(function() {
        $(this).next('.partner-offices').slideToggle(500);
    });
});

在上面,.partner-area 是要单击的 link 的 class,.partner-offices 是我的表单的 class 名称。这基本上是说,当单击任何 link 时,下一个表单将激活并打开。

表格中的默认 css display: hidden

因此,解决方案非常简单。我决定让用户 AJAX 即时构建表单,而不是为每个评论呈现表单,这会很慢。 这是 _comment 视图:

- if comment.id && comment.user
  li id="comment-#{comment.id}" class="comment"
    h6 = "From #{link_to comment.user.email, user_path(comment.user)}".html_safe
    .comment_body
      = comment.body
    = render 'shared/likes_panel', object: comment
    = link_to "Reply",
      new_comment_path(comment_id: comment.id),
      remote: true
    .comment_form

    - unless comment.comments.empty?
      = render 'comments/list', comments: comment.comments

如您所见,在 link_to 中我使用 remote: true,它指向 comments_controller 中的新 操作应响应 js:

def new
    @comment = @parent.comments.new
    @comment.user = current_user

    respond_to do |format|
      format.js
    end
  end

最后,您需要 new.js.erb 将评论表单附加到正确的评论中:

var li = $("#comment-<%= params[:comment_id] %>");
li.find(".comment_form").html("<%= j render 'comments/form' %>"); 

只要您在<ul>中发表评论,所有的子评论都会很好地缩进!