首页 > 解决方案 > Rails Geocoder 按距离排序

问题描述

我无法按距离对地理编码结果进行排序。对于我现在所拥有的,实现非常简单,但我似乎无法按距离对其进行排序,因为距离是在对象序列化时计算的。我正在尝试按distance_to_user属性排序,但结果只是以随机顺序返回。

locations_controller.rb

def index
        max = 250
        per_page = [(params[:per_page] || max).to_i, max].min
        offset   = params[:offset]
        @language ||= helpers.current_language

        location_scope = apply_scopes(Location).includes(store: [:language, :offers]).references(:stores)
                            .where('stores.language_id = ?', @language.id)
                            .reorder('locations.updated_at desc')
                            .assigned
        total_count = location_scope.count(:all)
        locations = location_scope.limit(per_page).offset(offset)
        render jsonapi: locations,
               include: [:store],
               expose: { user_location: user_location, language: @language },
               links: pagination_links(total_count, offset.to_i, per_page.to_i, @language, controller_name, action_name)
end

serializable_location.rb

class SerializableLocation < JSONAPI::Serializable::Resource
  type 'locations'
  attribute :shop_name
  attribute :full_address
  attribute :latitude
  attribute :longitude
  belongs_to :store
  attribute :distance_to_user do
    if @user_location.present?
      locale = @language.locale
      distance = Geocoder::Calculations.distance_between([@object[:longitude], @object[:latitude]], @user_location)
      converted_distance = LocationsHelper.convert_distance(locale, distance)
      ActionController::Base.helpers.number_to_human(converted_distance, units: :distance, format: "%n%u")
    end
  end
end

标签: ruby-on-railsrubyrails-geocoder

解决方案


推荐阅读