Ruby on rails 如何对记录进行分组和分页?

Ruby on rails 如何对记录进行分组和分页?,ruby-on-rails,kaminari,Ruby On Rails,Kaminari,我有一个通知模型: 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 在视图中,它

我有一个通知模型:

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发表了评论
用户2对post1发表了评论
用户3订阅了blog1
user4订阅了blog1

我如何按
应呈报
分组以显示:

用户1、用户2对post1发表了评论
用户3,用户4订阅了blog1


响应将取决于您使用的数据库

Postgresql 对于博士后,你可以这样做:

@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}" }
请注意,我猜到了其他表字段名,因此进行相应调整

基本思想是对结果进行分组并使用数据库连接功能。Kaminari和will_paginate将很高兴看到结果

注意:和往常一样,当您使用
#select
时,不要将对象写回数据库,否则它们将被损坏

MySql
对于mysql,这应该基本相同,但是将
string\u agg(users.user\u name,,)
替换为
group\u concat(users.user\u name)

在分页之前,您希望如何对当前用户的通知进行排序?您使用哪个数据库?