dimanche 20 novembre 2016

How to sort ActiveRecord Relation results on a custom logic?

I have a table containing a number of location objects(columns are id, latitude and longitude). I select rows from this table based on some query, then for these results, I want to find the distance of each location (using latitude and longitude of this point) from a custom point. How do I sort it on a manual logic? Here is what I tried:

# Location Model

def self.search(params, fields, user, employee_id)
    marker = SearchHelper.change_to_point(params[:marker_distance_sort])

    results = self.select(columns_selected)
            .intersect_query(boundary)

    # What should I do here for custom sorting?
    results.sort_by { |a, b| a.distance_from_marker(marker) <=> b.distance_from_marker(marker)}

end

def self.distance_from_marker(marker)
    marker.distance(FACTORY.point(self.attributes['longitude'], self.attributes['latitude']))
end

Sorry I am really new to ruby on rails and I have tried every resource available on stack overflow answers for custom sorting. Thanks for the help!

Aucun commentaire:

Enregistrer un commentaire