Using NULLS FIRST / NULLS LAST ordering in Rails
Methods nulls_first
& nulls_last
were added to Arel in Rails 6.1 for PostgreSQL and in most other databases in Rails 7.
In an earlier TIL, I showed how to order using Arel.
Procedure.order(Procedure.arel_table[:name].desc.nulls_first)
=> SELECT "procedures".* FROM "procedures" ORDER BY "procedures"."name" DESC NULLS FIRST
Procedure.order(Procedure.arel_table[:name].desc.nulls_last)
=> SELECT "procedures".* FROM "procedures" ORDER BY "procedures"."name" DESC NULLS LAST
Here the desc
method is wrapping the Arel attribute in a node so that it can be utilized in order
. nulls_first
/nulls_last
is just wrapping the previous ordering node.
Procedure.arel_table[:name].desc.nulls_first
=>
#<Arel::Nodes::NullsFirst:0x00007fb73ebf18f8
@expr=
#<Arel::Nodes::Descending:0x00007fb73ebf1920
@expr=
#<struct Arel::Attributes::Attribute
relation=
#<Arel::Table:0x00007fb735a02dc0
@klass=Procedure(id: integer, name: string, created_at: datetime, updated_at: datetime),
@name="procedures",
@table_alias=nil,
@type_caster=
#<ActiveRecord::TypeCaster::Map:0x00007fb735a02cd0
@klass=Procedure(id: integer, name: string, created_at: datetime, updated_at: datetime)>>,
name="name">>>
I mention this as you need to define the order before utilizing the nulls methods.
Tweet