1

I have two model Student and Information. Is this a order by nil?

Student | Information
Leo     | nil
Paul    | Some info1
Peter   | Some info2
Rex     | nil

How can I order it using active record and will show this result:

Student | Information
Paul    | Some info1
Peter   | Some info2
Rex     | nil
Leo     | nil

All nil Student.information.nil? will move down using ActiveRecord.

on-the-way
  • 120
  • 1
  • 10

2 Answers2

0

Maybe this topic can help you : Rails: Order with nulls last

Information.order('information_id IS NULL, information_id DESC')  # Null's last
Information.order('information_id IS NOT NULL, information_id DESC') # Null's first

If you are only using PostgreSQL, you can also do this

Information.order('information_id DESC NULLS LAST')  #Null's Last
Information.order('information_id DESC NULLS FIRST') #Null's First
Community
  • 1
  • 1
Didi
  • 248
  • 2
  • 18
0

You could do it like :

Student.information.order('id DESC') # For having nil first

OR

Student.all.order('information_id DESC')

By default, when you order in Ascending order, all nil are pushed down. So for reverse effect use DESC.

This solution will work for all irrespective of underlying database.

Disha
  • 776
  • 9
  • 19