The Little Things: Scopes for Alphabetization

Alphabetized. I see this scope pretty often, but it’s so easy to fat finger a letter and get an error. And maybe it’s just me, but it’s also a bit of a tongue twister.

# Rails User model
scope :alphabetized, -> { order(name: :asc) }
scope :reverse_alphabetized, -> { order(name: :desc) }
User.alphabetized
# Ecto
def alphabetized(query) do
query |> order_by(name: :asc)
end

Instead try using a_to_z and z_to_a:

# Rails
scope :a_to_z, -> { order(name: :asc) }
scope :z_to_a, -> { order(name: :desc) }
# ...or if you want to sort dynamically
scope :a_to_z, ->(field) { order(field => :asc)
User.a_to_z
User.a_to_z(:company_name) # alphabetized by company name
# Ecto
def a_to_z(query) do
query |> order_by(name: :asc)
end
def z_to_a(query) do
query |> order_by(name: :desc)
end

It’s a little thing, but it might make you and your coworkers a bit happier. Give it a try on your next project.