问题描述
我无法按距离对地理编码结果进行排序。对于我现在拥有的实现来说,实现非常简单,但我似乎无法按距离对其进行排序,因为距离是在对象序列化时计算的。我正在尝试按 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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)