List results by scope where (field) not nil THEN second condition

363 Views Asked by At

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.

1

There are 1 best solutions below

0
On

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)