【问题标题】:Using rails gem geokit sort by distance and pagination?使用rails gem geokit按距离和分页排序?
【发布时间】:2011-04-17 02:26:33
【问题描述】:

我在我的应用程序中遇到了一个小问题。我目前正在使用 geokit 来查找给定位置附近的对象,并且我在找到的集合上使用 sort_by_distance_from。

见下文:

@find = Item.find(:all, :origin =>[self.geocode.lat.to_f,self.geocode.lng.to_f], :within=>50, :include=>[:programs], :conditions=>["programs.name = ?", self.name])
  @find.sort_by_distance_from([self.geocode.lat.to_f,self.geocode.lng.to_f]

geokit 有什么方法可以在按距离排序时对数据库进行分页吗?

AKA,没有调用完整的搜索结果?

【问题讨论】:

  • 我也在为此寻找解决方案。与 will_paginate 结合会产生不正确的结果。

标签: ruby-on-rails pagination geokit


【解决方案1】:

距离列不再起作用:

“在当前版本的 geokit-rails 中,无法使用距离列添加 where 子句。我尝试了许多不同的方法来做到这一点,但都没有成功。”

where 和 order 子句的行为方式相同。

人们期望构建这样的查询:

scoped  = Location.geo_scope(:origin => @somewhere)
scoped  = scoped.where('distance <= 5')
results = scoped.all

目前无法做到这一点,必须像这样一步完成:

scoped = Location.within(5, :origin => @somewhere)
results = scoped.all

github.com/geokit/geokit-rails

【讨论】:

    【解决方案2】:

    我解决这个问题的方法是使用 find() 的 :offset 和 :limit 参数

    此外,geokit 模型还有一个距离场,:order=>'distance asc'

    例如。

    page = 0 unless params[:page]
    items_per_page = 20
    offset = page * items_per_page
    @find = Item.find(:all, :origin =>[self.geocode.lat.to_f,self.geocode.lng.to_f], :within=>50, :include=>[:programs], :conditions=>["programs.name = ?", self.name], :order => 'distance asc', :limit => items_per_page, :offset => page)
    

    【讨论】:

    • 距离列不再起作用:“在当前版本的 geokit-rails 中,无法使用距离列添加 where 子句。我尝试了许多不同的方法这并没有让它发挥作用。”对于 where 和 order 子句,它的行为方式相同。 github.com/geokit/geokit-rails