gpt4 book ai didi

javascript - rails 4 : append partial to hidden div upon AJAX call

转载 作者:行者123 更新时间:2023-11-28 18:54:40 26 4
gpt4 key购买 nike

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

一个帖子有 has_many 条评论和一条评论 belong_to 一条帖子。

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

<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,然后附加新的评论评论?

最佳答案

按照 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>

在 View 中

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

另一个选项是重构 View UI,以便显示评论标题,并在表单中显示“尚无评论”或“输入第一条评论”作为提示。然后,列表的空 div 就已经正常渲染和显示了。

关于javascript - rails 4 : append partial to hidden div upon AJAX call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33837484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com