gpt4 book ai didi

css - 如何创建评论 View ? Facebook 点赞评论实现(ruby on rails)

转载 作者:太空宇宙 更新时间:2023-11-03 16:53:39 25 4
gpt4 key购买 nike

我在我的页面上实现了一个类似于 facebook 的评论,但我正在尝试弄清楚如何让 View 正常工作。

下面是评论如何工作的代码:

评论 Controller

class CommentsController < ApplicationController
def create
@micropost = Micropost.find(params[:micropost_id])
@comment = Comment.new(params[:comment])
@comment.micropost = @micropost
@comment.user = current_user
if @comment.save
redirect_to(:back)
else
render 'shared/_comment_form'
end
end
end

评论表单 View

<%= form_for([micropost, @comment]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_field :comment_content %>
</div>
<button class="btn" type="submit">
Comment
</button>
<% end %>

我正试图弄清楚如何在提交后最好地显示这些评论。我可以用它来构建 View 吗??

评论.html.erb

  <%= simple_format(comment.content) %>
<% end %>

最佳答案

你可以这样做

class CommentsController < ApplicationController
def create
@micropost = Micropost.find(params[:micropost_id])
@comment = Comment.new(params[:comment])
@comment.micropost = @micropost
@comment.user = current_user
if @comment.save
flag = true
else
flag = false
end

respond_to do |format|
format.html {flag ? redirect_to(:back) : render 'shared/_comment_form'}
format.js
end

end
end

将表单更改为 ajaxified

<%= form_for([micropost, @comment], remote: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_field :comment_content %>
</div>
<button class="btn" type="submit">
Comment
</button>
<% end %>

然后稍微修改一下你的 View

评论/comment.html.erb

<%= render partial: 'comments/comment', locals: {comment: @comment} %>

部分将是

_comment.html.erb

<div id="comment-<%= comment.id%>">
<%= simple_format(comment.content) %>
<% end %>
</div>

然后在 comments/create.js.erb 中做

$("#comments_container").prepend(' <%=j render partial: "comments/comment", locals: {comment: @comment} %>');

您可以制作任何您想要的动画,而不是预先添加。您也可以追加,具体取决于您希望如何对评论进行排序

请注意,我为此使用了 jQuery。 #comments_container 是要放置评论的div

请注意,create.js.erb 基本上是评论 Controller 中创建操作的 js View ,因此它可以访问创建操作具有的任何变量

注意 2:我使用的是 ruby​​ 1.9 哈希格式

注3:我将评论命名为#comment-<%= comment.id %>因此,如果您想删除它或以其他方式处理它,您可以稍后访问它,例如

def destroy

@comment = Comment.find(params[:id])

respond_to do |format|
format.js
end
end

然后在 destroy.js.erb 中做

$("#comment-<%= @comment.id %>").remove();

这将删除那个div

确保有 jquery_ujs 和 jquery gem/files 就差不多了..

关于css - 如何创建评论 View ? Facebook 点赞评论实现(ruby on rails),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15328300/

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