首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何分组和分页记录?

问如何分组和分页记录?
EN

Stack Overflow用户
提问于 2013-09-21 10:19:05
回答 1查看 2.3K关注 0票数 1

我有一个通知模型:

代码语言:javascript
复制
Notification(id: integer, notifiable_id: integer, notifiable_type: string, user_id: integer, created_at: datetime, updated_at: datetime)

通知控制器:

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-21 11:51:21

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

Postgresql

对于postgres,您可以这样做:

代码语言:javascript
复制
@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)

然后,使用这样的累加对象:

代码语言:javascript
复制
@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 )

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18931460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档