Skip to content

Instantly share code, notes, and snippets.

@jvans1
Created March 18, 2013 15:44
Show Gist options
  • Save jvans1/5188109 to your computer and use it in GitHub Desktop.
Save jvans1/5188109 to your computer and use it in GitHub Desktop.
Joins with ordering solution
#Issues
# THIS WORKS: search = Company.search(:users_orders_line_items_price_gte => "2", :order => :ascend_by_orders_total )
#since there is an association in the ordering, the scope returned from the first conditions runs through the stack and hits the join class creating the
#necessary join. When this happens it creates a new set of joins values for the scope
# so I can call joins_values on scope, choose the last one and order based on that.(...order("orders.total ASC"))
#This don't: search = Company.search(:users_orders_line_items_price_gte => "2", :order => :ascend_by_identifier )
#Since there is no association in the ordering method, it never runs through the 'joins' class. So when I call joins_values
#on the current scope i get backk {:users => {:orders => :line_items}} since the last value is line_item, i obviously don't
#want to order on that.
#Fix:
#my fix checks to see if the value following ascend_by_ is a column of the current klass, if so it orders using the
#current klass (...order("companies.indentifier ASC")) otherwise it assumes that you want to be ordering on the last
#value in the joins_value hash
def scope
if applicable?
##add specific column to order on in all ordering queries
klass.joins(join).order("#{order_on.to_s.pluralize}.#{sort_on} DESC")
end
end
def order_on
joins_values = Array(klass.scoped.joins_values.flatten.try(:last)).flatten
potential_column = /descend_by_/.match(method_name).post_match
if klass.column_names.include?(potential_column)
klass.name.underscore.pluralize
else
Array(joins_values.last).flatten.last
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment