在Postgres中使用子查询的Rails分页查询

时间:2015-12-30 21:44:00

标签: ruby-on-rails postgresql ruby-on-rails-4 pagination kaminari

我有以下Postgres查询:

SELECT p.*
FROM   unnest('{19082, 19075, 20705, 18328, 19110, 24965, 18329, 27600
              , 17804, 20717, 27598, 27599}'::int[]) s(source_id)
     , LATERAL (
   SELECT *
   FROM   posts
   WHERE  source_id = s.source_id
   AND    deleted_at IS NULL
   ORDER  BY external_created_at DESC
   LIMIT  100
   OFFSET 0
   ) p
ORDER  BY p.external_created_at DESC
LIMIT  100
OFFSET 0;

我已将其转换为ActiveRecord查询,如下所示:

source_ids = '19082, 19075, 20705, 18328, 19110, 24965, 18329, 27600, 17804, 20717, 27598, 27599'
subquery = Post.where('source_id = s.source_id AND deleted_at IS NULL')
           .order('external_created_at DESC')
Post.select('p.*')
 .from("unnest('{#{source_ids}}'::int[]) s(source_id), LATERAL (#{subquery.to_sql}) p")
 .order('p.external_created_at DESC')

我想在此添加Kaminari分页。

但问题是,要使查询正常工作,我必须将LIMITOFFSET添加到主查询和子查询中。

如果我只是这样修改它:

source_ids = '19082, 19075, 20705, 18328, 19110, 24965, 18329, 27600, 17804, 20717, 27598, 27599'
subquery = Post.where('source_id = s.source_id AND deleted_at IS NULL')
           .order('position, external_created_at DESC')
           .per(100).page(1)
Post.select('p.*')
 .from("unnest('{#{source_ids}}'::int[]) s(source_id), LATERAL (#{subquery.to_sql}) p")
 .order('p.position, p.external_created_at DESC')
 .per(100).page(1)

我得到undefined method 'per' for #<Post::ActiveRecord_Relation:0x007f9682f540e0>

有任何想法或建议吗?

1 个答案:

答案 0 :(得分:2)

这可能看起来有些愚蠢,但您是否尝试在查询中.page之前调用.per?那么Post.where("...").order("...").page(1).per(100)

如果这不起作用,Kaminari可以对数组进行分页。尝试使用.to_a将结果转换为数组,然后使用paginate_array辅助方法。

https://github.com/amatsuda/kaminari#paginating-a-generic-array-object