Browse files

fixed problem with order when using include

git-svn-id: 9265c765-0211-4c68-b2df-6d1bd6e20c4d
  • Loading branch information...
1 parent 83065dc commit 60813cd17f9ed59196c02598d4c45c3184c1317b lewisac committed Jun 20, 2007
Showing with 12 additions and 1 deletion.
  1. +12 −1 lib/geo_kit/acts_as_mappable.rb
13 lib/geo_kit/acts_as_mappable.rb
@@ -213,11 +213,22 @@ def prepare_for_find_or_count(action, args)
substitute_distance_in_conditions(options, origin, units, formula) if origin && options.has_key?(:conditions)
# Order by scoping for find action.
apply_find_scope(args, options) if action == :find
+ # Unfortunatley, we need to do extra work if you use an :include. See the method for more info.
+ handle_order_with_include(options,origin,units,formula) if options.include?(:include) && options.include?(:order) && origin
# Restore options minus the extra options that we used for the
# GeoKit API.
+ # If we're here, it means that 1) an origin argument, 2) an :include, 3) an :order clause were supplied.
+ # Now we have to sub some SQL into the :order clause. The reason is that when you do an :include,
+ # ActiveRecord drops the psuedo-column (specificically, distance) which we supplied for :select.
+ # So, the 'distance' column isn't available for the :order clause to reference when we use :include.
+ def handle_order_with_include(options, origin, units, formula)
+ # replace the distance_column_name with the distance sql in order clause
+ options[:order].sub!(distance_column_name, distance_sql(origin, units, formula))
+ end
# Looks for mapping-specific tokens and makes appropriate translations so that the
# original finder has its expected arguments. Resets the the scope argument to
# :first and ensures the limit is set to one.
@@ -435,7 +446,7 @@ def normalize_point_to_lat_lng(point)
# and finally sorts the array by the resulting distance.
class Array
def sort_by_distance_from(origin, opts={})
- distance_attribute_name = opts.delete(:distance_attribute_name) || 'distance'
+ distance_attribute_name = opts.delete(:distance_attribute_name) || 'distance'
self.each do |e|
e.class.send(:attr_accessor, distance_attribute_name) if !e.respond_to? "#{distance_attribute_name}="
e.send("#{distance_attribute_name}=", origin.distance_to(e,opts))

0 comments on commit 60813cd

Please sign in to comment.