Skip to content

Instantly share code, notes, and snippets.

@kardeiz
Created September 19, 2012 19:19
Show Gist options
  • Save kardeiz/3751638 to your computer and use it in GitHub Desktop.
Save kardeiz/3751638 to your computer and use it in GitHub Desktop.
Fix for ActiveRecord::Relation not including ORDER BY columns in SELECT statement
# Fix for ActiveRecord::Relation not including ORDER BY columns in SELECT statement (in PostgreSQL)
# e.g., ActionView::TemplateError (PGError: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
# Note: use at your own risk. This works on my data but your results may vary.
def add_order_values_to_select(arel_object)
my_order_values = arel_object.order_values.map do |x|
x = x.to_sql if x.respond_to? :to_sql
x.gsub(/ASC|asc|desc|DESC|"/,"").strip
end.reject(&:blank?)
my_order_values.blank? ? arel_object : arel_object.select( (arel_object.select_values + my_order_values).flatten )
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment