我有一个通知模型:
Notification(id: integer, notifiable_id: integer, notifiable_type: string, user_id: integer, created_at: datetime, updated_at: datetime)通知控制器:
def index
@notifications = current_user.notifications.page(params[:page]).per(10)
end鉴于此,它将记录显示为:
user1对post1的评论 user2对post1的评论 user3订阅了blog1 user4订阅了blog1
如何按notifiable分组显示:
user1,user2对post1的评论 user3,user4订阅了blog1
发布于 2013-09-21 11:51:21
响应将取决于您使用的数据库。
Postgresql
对于postgres,您可以这样做:
@notifications = current_user.notifications.
select( "string_agg( users.user_name, ', ' ) as user_names, notifiables.name as notifiable_name" ).
group( 'notifiables.name, notifications.notifiable_type' ).
joins( :notifiable ).joins( :user ).
page(params[:page]).per(10)然后,使用这样的累加对象:
@notifications.map { |n| "#{n.user_names} #{n.notifiable_type} #{n.notifable_name}" }请注意,我已经猜到了其他表的字段名,因此相应地进行调整。
其基本思想是将结果分组并使用数据库连接特性。卡米纳里和will_paginate将愉快地处理这个结果。
注意:与往常一样,在使用#select时,不要将对象写回数据库,否则它们会损坏。
MySql
对于mysql,这应该基本相同,但是将string_agg( users.user_name, ', ' )替换为group_concat( users.user_name )
https://stackoverflow.com/questions/18931460
复制相似问题