Michael Durrant
Michael Durrant

Reputation: 96564

Rails - how can I have a Class level method in an active record model that sorts by lower case?

In ruby I can do my_ar_collection.sort_by{ |element| element.name.downcase} in my controller.

I want to have an ActiveRecord class method that does that.

Right now I have:

def self.ordered
  order(:name)
end 

But I want to add .downcase to it. I've tried a number of ways, such as using sort_by and using order :field.downcase but with no luck

Upvotes: 0

Views: 98

Answers (1)

Michael Durrant
Michael Durrant

Reputation: 96564

This code works:

Use order("lower(name)")

but is not ideal as it used a sql function not a ruby function so is database independent - that said - lower() does exist in most sql implementations, including mySQL, Postgres, sqlserver and Oracle. But for this and other, similar operations I would prefer to use a Ruby approach.

Upvotes: 1

Related Questions