0

我在我的观点中使用它来查看它是否有效,并且它是:

<%= post.comments if post.comments.present? %>

该代码所做的是提取与帖子相关的评论列表。

它以这种格式显示在我的网页上:

[#<Comment id: 12, content: nil, user_id: 9, post_id: 18, created_at: "2013-03-12 04:51:47", updated_at: "2013-03-12 04:51:47", comment_content: "check">, #<Comment id: 13, content: nil, user_id: 9, post_id: 18, created_at: "2013-03-12 04:52:11", updated_at: "2013-03-12 04:52:11", comment_content: "check">] 

我觉得我几乎已经有了后端代码,我只需要正确显示视图。

如何comment_content以列表格式(如典型评论框)仅显示用户名和给定帖子 ID?我已经按升序使用:

default_scope order: 'comments.created_at ASC'
4

3 回答 3

0

假设您的用户有一个name属性,您将不得不像这样遍历每个评论:

<% if post.comments.exists? %>
  <% post.comments.each do |comment| %>
    User: <%= comment.user.name %>
    Comment: <%= comment.comment_content %>
  <% end %>
<% end %>
于 2013-03-12T06:13:48.470 回答
0
<% if post.comments.present? %>
  <table>
    <tr>
     <th>Name</th>
     <th>Content</th>
    </tr>
    <% post.comments.each do |comment| %>
    <tr>
       <td><%= comment.user.name %></td>
       <td><%= comment.comment_content %></td>
    </tr>
    <%end%>
<%end%>   

这用于显示您视图中所有评论的用户名和内容。

于 2013-03-12T06:14:41.027 回答
0

如果你需要显示评论、用户和用户的 Gravatar,请尝试以下操作:

<% if post.comments.exists? %>
    <% post.comments.each do |comment| %>
        <%= image_tag("http://www.gravatar.com/avatar.php?gravatar_id=#{Digest::MD5::hexdigest(comment.user.email)}", :alt => 'Avatar', :class => 'avatar') %> <!-- Retrieves Gravatar -->
        <%= comment.user.name %>
        <%= comment.comment_content %>
    <% end %>
<% end %>

这假设您拥有用户的电子邮件,并且用户拥有 Gravatar。

于 2013-03-12T06:32:06.833 回答