문제

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