Order Rails Query by Virtual Attribute

Oct 22, 2014 Ruby on Rails

Have you tried and failed to order a rails query by a virtual attribute, being told the column isn't in the database (when, in fact, you already knew that)?

Let's say you have a User model that has a name attribute that you've split up on the fly. Something like this.

class User < ActiveRecord::Base

  def first_name
    return email if name.nil?
    name.split(' ').first

  def last_name
    return email if name.nil?
    name.split(' ').last


You've probably tried and failed with a scope like this.

scope :by_name, -> { order('last_name asc') }

What you have to do is first load the objects you want into memory and then use Ruby's sort_by array method to sort the collection of objects. So, something like this would work.

scope :by_name, -> { all.to_a.sort_by(&:last_name) }

Did you learn something or find this article interesting?

If so, why not