【问题标题】:Rails 4: append partial to hidden div upon AJAX callRails 4:在 AJAX 调用时将部分附加到隐藏的 div
【发布时间】:2015-11-20 23:01:05
【问题描述】:

在我的 Rails 4 应用程序中,我有一个 Post 和一个 Comment 模型。

一个帖子has_many cmets 和一个评论belong_to 一个帖子。

用户可以在帖子show.html.erb 视图上使用表单创建新评论:

<h2 class="center">COMMENT ON THIS POST</h2>
        <%= form_for [@post, @post.comments.build], remote: true do |f| %>
          <p>
            <%= f.text_area :body, id: 'new_comment_body', placeholder: "Write your comment here..." %>
          </p>
          <p>
            <%= f.submit "CREATE COMMENT", id: 'comment_submit' %>
          </p>
        <% end %>

这是我的comments_controllers.rb

def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.build(comment_params)
    @comment.user_id = current_user.id
    respond_to do |format|
      if @comment.save
        format.html { redirect_to :back }
        format.json { render :show, status: :created, location: @comment }
        format.js
      else
        format.html { render :new }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

通过 AJAX 调用,我能够将新创建的评论添加到页面:

# comments/create.js.erb

$('#post_show_comments').append("<%= j render @comment %>");

问题是,如果帖子还没有评论,#post_show_comments div 不会显示:

<% if @post.comments.any? %>
  <hr>
  <h2 class="center">COMMENTS</h2>
    <div id="post_show_comments">
      <%= render @comments %>
    </div>
<% end %>

正因为如此,当一个帖子的第一条评论被创建时,它并没有附加到div中,用户需要手动重新加载页面才能看到评论出现。

如果还没有评论,如何修改comments/create.js.erb文件的内容以显示#post_show_comments div,然后追加新评论?

【问题讨论】:

  • 你可以在附加评论之前使用 jquery 来显示 div 吗?类似 $("#post_show_cmets).show();
  • 当然。我应该在comments/create.js.erb 之前的$('#post_show_comments').append("&lt;%= j render @comment %&gt;"); 之前插入这行代码吗?另外,我应该执行任何条件来检查 div 是否已经显示?
  • 我实际上只是尝试过(我在评论中提到的)但它还没有工作。
  • 你的控制器是什么样子的?
  • 我刚刚使用控制器中的代码更新了问题。但我不确定问题出在控制器上,因为当帖子已经有评论时一切正常(因此显示#post_show_comments)。我猜这个问题来自 JS 代码,但我不知道哪里出了问题。

标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4


【解决方案1】:

按照 OscuroAA 的建议

<div id="post_show_comments_wrapper" style="<%= "display:none" if @post.comments.none? %>"> 
  <hr>
  <h2 class="center">COMMENTS</h2>
    <div id="post_show_comments">
      <%= render @comments %>
    </div>
</div>

在视图中

# comments/create.js.erb
$('#post_show_comments_wrapper').show();
$('#post_show_comments').append("<%= j render @comment %>");

另一个选项是重组视图 UI,以便显示 cmets 标题并显示“还没有 cmets”或“输入第一条评论”作为提示以及表单。然后,列表的空 div 就已经正常渲染和显示了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多