Category has many Post.

I want a collection (of the AssociationRelation class) with:

all posts that has the attribute published_at set to nil

TOGETHER WITH

the post with the most recent "published_at" date

Separately the two queries look like the following:
.where("published_at is NULL")
.order(published_at: :desc).limit(1)

But how could I have a collection that's the result of both?

有帮助吗?

解决方案

Use partition

recent, rest = Post.order('published_at DESC').partition{ |e| e[:published_at] != nil }
recent_one = Array.new << recent.first
@posts = recent_one + rest

So, in @posts the first post will be the most recently published post and the rest will be with published_at nil

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top