Reputation: 2921
I have a have_many association that I would like to sort so that the case is agnostic. Currently it looks like this:
class Account < ActiveRecord::Base
has_many :studies, order: :name
which sorts capital letters first then lower case giving results like
DP
De
I'd like the sorting to be case agnostic i.e.
De
DP
I've been able to do this in the model method, e.g.,
def studies
account.studies.sort_by! { |s| s.name.downcase }
end
Is it possible to sort in the has_many association using order: so that the result is case agnostic?
Upvotes: 0
Views: 148
Reputation: 527
This should work if you'r using mysql
has_many :studies, order: 'lower(name)'
lower
is a mysql function that is equivalent to downcase in ruby.
So since in Rails you can customize the order clause using SQL fragments you essentially can use any database vendor specific functionality that you want.
Upvotes: 1