Pregunta

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?

¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top