glebm / order_query

Find next / previous Active Record(s) in one query

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Wrong order?

vitobotta opened this issue · comments

Hi! I am trying to use this gem in a CMS, to show the previous/next post related to the current one, and sorted by publishing date.

In my dev environment, if I run

blog.
    documents.
    published.
    posts.
    order(published_at: :asc).
    pluck(:id)

I get these IDs:

[195, 209, 210, 212, 213, 214, 215, 216, 217, 218, 255, 257, 258, 259, 260, 261, 262, 263]

If I ask the previous of 255 for example, I get 218 as expected. However if I ask for the next document, I get 263 instead of 257. But both of the queries generated seem to be wrong:

Previous

SELECT "documents".* FROM "documents" WHERE "documents"."blog_id" = $1 AND "documents"."published" = $2 AND "documents"."type" = $3 AND ("documents"."published_at" <= '2020-05-08 17:56:08.844567' AND ("documents"."published_at" < '2020-05-08 17:56:08.844567' OR "documents"."published_at" = '2020-05-08 17:56:08.844567' AND "documents"."id" < 255)) ORDER BY "documents"."published_at" DESC, "documents"."id" DESC LIMIT $4

Next

SELECT "documents".* FROM "documents" WHERE "documents"."blog_id" = $1 AND "documents"."published" = $2 AND "documents"."type" = $3 AND ("documents"."published_at" >= '2020-05-08 17:56:08.844567' AND ("documents"."published_at" > '2020-05-08 17:56:08.844567' OR "documents"."published_at" = '2020-05-08 17:56:08.844567' AND "documents"."id" > 255)) ORDER BY "documents"."published_at" DESC, "documents"."published_at" ASC, "documents"."id" ASC LIMIT $4

So for some reason order_query adds a where clause for the ID, which is incorrect. I only want to sort by publishing date (published_at).

The scope I give to order_query is as follow:

    scope = Current.blog.
    documents.
    published.
    posts

    @related ||= scope.order_related_at(@document)

And in the document model I have this:

order_query :order_related, [:published_at, :asc]

What am I missing?

Thanks a lot in advance!

Nevermind, I actually had a difference in the scope. Thanks