1

Ich habe zwei Modell Student und Information. Ist das ein Auftrag von Null?Verschieben Sie alle nil abhängigen Wert mit ActiveRecord

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

Wie kann ich es mit aktiven Datensatz zu bestellen und wird dieses Ergebnis zeigen:

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

Alle nil Student.information.nil? bewegt sich mit ActiveRecord nach unten.

Antwort

0

Vielleicht kann dieses Thema Ihnen helfen: 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 

Wenn Sie nur PostgreSQL verwenden, können Sie dies auch

Information.order('information_id DESC NULLS LAST') #Null's Last 
Information.order('information_id DESC NULLS FIRST') #Null's First 
0

Sie könnten es mögen:

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

ODER

Student.all.order('information_id DESC') 

Wenn Sie in Aufsteigender Reihenfolge bestellen, werden standardmäßig alle Nuls nach unten geschoben. Verwenden Sie daher für den umgekehrten Effekt DESC.

Diese Lösung funktioniert für alle unabhängig von der zugrunde liegenden Datenbank.

+0

Bitte lassen Sie mich wissen, wenn es geholfen hat. – Disha