0

I'm wondering if there's a way to make one query to get the following conditions:

1) scope :scheduled_for, -> {where.not(:scheduled_for => nil)}

then

2) scope :sort_by_position, -> {order('position')}

The expected result would be the following list:

  • Post 1 (Sept 23 && Position 1)
  • Post 2 (Sept 24 && Position 2)
  • Post 3 (Position: 3)
  • Post 4 (Position: 4)
  • etc...

Note: the position field could be random (i.e. Post 1 could have a position of 5 but since its scheduled_for is not empty, it takes precedence over a lower position post.

Vincent
  • 147
  • 10
  • What's wrong with `Model.scheduled_for.sort_by_position` ? That will only do the query when results are accessed, so it'll only be one query. – SteveTurczyn Sep 23 '16 at 13:09
  • This only gives part of the result, i.e. a list of posts with scheduled_for and position NOT NIL. It doesn't give the second part of the list (where scheduled_for NIL and position NOT NIL) – Vincent Sep 24 '16 at 07:31

1 Answers1

0

You can specify multiple conditions in the order_by

order_by('scheduled_for IS NULL, position')

scheduled_for IS NULL returns "1" if true, "0" is false, so NULL values are greater (i.e. show up at the end of the list)

SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53