如何为注释创建视图?Facebook类评论实现(ruby on rails)



我在我的页面上实现了一个facebook喜欢的评论,但我正试图找出如何让视图工作。

下面是注释如何工作的代码:

评论控制器

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

注释表单视图

<%= 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 %>

我正试图找出如何最好地显示这些评论提交后。我可以用这个来构建视图吗??

comment.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

将您的表单更改为ajax

<%= 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 %>

然后编辑您的视图位

评论/comment.html.erb

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

,部分将是

_comment.html.erb

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

then in comments/create.js。erb做

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

而不是prepend,你可以做任何你想要的动画。你也可以追加,这取决于你想如何排序你的评论

注意我使用jQuery。#comments_container是要放置注释的div

注意,create。js.erb基本上是评论控制器中创建操作的js视图因此它可以访问创建操作的任何变量

note2:我使用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/文件,差不多就这些了

最新更新