我决定另外发一篇回答,因为第一篇已经变得非常冗长。
要像你在示例中提到的那样将评论通知呈现为可展开列表,首先需要收集针对某个目标用户具有通知的评论(不要忘记在Comment模型中添加
has_one:notification
)。
comments = Comment.joins(:notification).where(:notifications => { :target_user_id => current_user.id })
请注意,这里使用的
joins
生成了一个
INNER JOIN
,因此您可以正确地排除任何没有通知的评论(因为某些通知可能已被用户删除)。
接下来,您需要按其可评论对象对这些评论进行分组,以便为每个可评论对象创建可展开列表。
@comment_groups = comments.group_by { |c| "#{c.commentable_type}#{c.commentable_id}"}
这将生成一个哈希值,例如
`{ 'Photo8' => [comment1, comment2, ...], 'Event3' => [comment1, ...], ... }`
现在你可以在你的视图中使用它了。
在 some_page_showing_comment_notifications.html.erb
中。
...
<ul>
<% @comment_groups.each do |group, comments| %>
<li>
<%= render 'comment_group', :comments => comments, :group => group %>
</li>
<% end %>
</ul>
...
In _comment_group.html.erb
<div>
<% case comments.length %>
<% when 1 %>
<%= comments[0].commenter.name %> commented on your <%= comment[0].commentable_type.downcase %>.
<% when 2 %>
<%= comments[0].commenter.name %> and <%= comments[1].commenter.name %> commented on your <%= comment[0].commentable_type.downcase %>.
<% when 3 %>
<%= comments[0].commenter.name %>, <%= comments[1].commenter.name %> and <%= comments[2].commenter.name %> commented on your <%= comment[0].commentable_type.downcase %>
<% else %>
<%= render 'long_list_comments', :comments => comments, :group => group %>
<% end %>
</div>
在IT相关领域,翻译为中文:
在_long_list_comments.html.erb
文件中。
<div>
<%= comments[0].commenter.name %> and <%= comments.length-1 %> others commented on your <%= comments[0].commentable_type %>.
<%= button_tag "+", class: "expand-comments-button", id: "#{group}-button" %>
</div>
<%= content_tag :ul, class: "expand-comments-list", id: "#{group}-list" do %>
<li>
<% comments.each do |comment| %>
# render each comment in the same way as before
<% end %>
</li>
<% end %>
最后,向
button.expand-comments-button
添加一些 JavaScript 来切换
ul.expand-comments-list
的
display
属性应该是一个简单的问题。每个按钮和列表都有基于评论组键的唯一 ID,因此您可以使每个按钮展开正确的列表。