Searchlogic, Postgres, and Case Insensitive Ordering
Posted by gabe-fuzz
Unfortunately when using postgres the default ordering is case sensitive such that all Capitalized values come before all lowercase values. This seems counter intuitive and certainly not desired in my project. As far as I can tell there is currently no support for case insensitive ordering with searchlogic. I was able to solve this by adding two new named_scopes in Searchlogic::NamedScopes::Ordering.create_ordering_conditions like so:
named_scope("iascend_by_#{column}".to_sym, {:order => "upper(#{table_name}.#{column}) ASC"})
named_scope("idescend_by_#{column}".to_sym, {:order => "upper(#{table_name}.#{column}) DESC"})
Search logic rocks, and I know it’s bad practice to be hacking plugins so I’m hoping this will be included in the next release. There were a couple other subtle changes that I had to make to get it to work. To use this patch, copy the below code into /config/initializers/searchlogic_extensions.rb:
module Searchlogic
module NamedScopes
module Ordering
def ordering_condition_details(name)
# raise name.to_s
if name.to_s =~ /^(ascend|descend|iascend|idescend)_by_(#{column_names.join("|")})$/
{:order_as => $1, :column => $2}
elsif name.to_s =~ /^order$/
{}
end
end
def create_ordering_conditions(column)
named_scope("ascend_by_#{column}".to_sym, {:order => "#{table_name}.#{column} ASC"})
named_scope("descend_by_#{column}".to_sym, {:order => "#{table_name}.#{column} DESC"})
named_scope("iascend_by_#{column}".to_sym, {:order => "upper(#{table_name}.#{column}) ASC"})
named_scope("idescend_by_#{column}".to_sym, {:order => "upper(#{table_name}.#{column}) DESC"})
end
end
module AssociationOrdering
private
def association_ordering_condition_details(name)
associations = reflect_on_all_associations.collect { |assoc| assoc.name }
if name.to_s =~ /^(ascend|descend|iascend|idescend)_by_(#{associations.join("|")})_(\w+)$/
{:order_as => $1, :association => $2, :condition => $3}
end
end
end
end
end
You can now use MyObject.iascend_by_name and MyObject.idescend_by_name.
Tags: ruby on rails / ruby / rails / searchlogic / postgres / order / named_scopes /