【问题标题】:How to create a view for comments? Facebook like comments implemented (ruby on rails)如何创建评论视图?实现 Facebook 点赞评论(ruby on rails)
【发布时间】:2013-02-26 00:32:18
【问题描述】:

我在我的页面上实现了一个类似 cmets 的 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 %>

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

comment.html.erb

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

【问题讨论】:

标签: css ruby ruby-on-rails-3 partial-views


【解决方案1】:

你可以这样做

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

然后稍微编辑您的视图

cmets/comment.html.erb

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

部分将是

_comment.html.erb

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

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

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

你可以做任何你想要的动画,而不是预先设置。您也可以附加,具体取决于您希望如何对 cme​​ts 进行排序

请注意,我为此使用了 jQuery。 #cmets_container 是您要放置 cmets 的 div

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

note2:我使用的是 ruby​​ 1.9 哈希格式

注意3:我将评论命名为#comment-&lt;%= comment.id %&gt;,以便您以后可以在以后访问它,如果您想删除它或以其他方式处理它,例如

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,仅此而已..

【讨论】:

    猜你喜欢
    • 2011-11-30
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    相关资源
    最近更新 更多