我决定发布这个作为另一个答案,因为第一个得到了可笑的长。
要渲染留言通知可扩展列表,你在你的 例子注意,首先收集有一些目标用户通知的意见(不要忘了添加has_one :notification
到Comment
模型)。
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>
...
在_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>
在_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 %>
最后,它应该是一个简单的事情,一些JavaScript添加到button.expand-comments-button
来切换display
ul.expand-comments-list
的财产。每个按钮和列表都有基于注释组键的唯一ID,因此您可以使每个按钮展开正确的列表。
这将为我节省很多麻烦,所以我添加了赏金作为赞赏的象征,但是我不能将它分配到24小时之后。 – Duopixel
@Duopixel非常感谢!让我知道你是否需要扩展任何东西。 – cdesrosiers
谢谢。我也成功了,但没有观察员的一部分。我现在只需要像after_create一样。但是,我怎样才能展示我所给出的例子。就像发布用户的前几个名字一样,发表评论? – index