通过查询最新状态更新位置查找特定位置的用户

时间:2011-03-14 17:14:42

标签: ruby-on-rails geokit

我正在开发一个与Twitter非常相似的Rails应用程序,用于通过称为“ping”的状态更新来跟踪团队成员及其更新状态。 Twitter称这些状态为“推特”。

申请的要点是:

员工(:first_name,:last_name)
Ping(:datetime,:status,:latitude,:longitude)

员工模型:

class Employee < ActiveRecord::Base
  has_many :pings
  has_one  :ping, :order => "created_at DESC" # Returns the lastest Ping (employee.ping)
end

Ping模型:

class Ping < ActiveRecord::Base
  belongs_to :employee
  acts_as_mappable  :default_units => :miles,
                    :default_formula => :sphere,
                    :distance_field_name => :distance,
                    :lat_column_name => :latitude,
                    :lng_column_name => :longitude
end

我需要通过当前位置查询所有员工的最新 ping。问题是我不知道该怎么做。

如果我搜索当前位置的所有ping,我会获得属于员工的多个ping。然后,我必须将每个 ping.id employee.ping.id 进行比较,看看其中一个是否是该员工的最新ping。

我无法通过Employee进行搜索,因为地理位置信息位于Ping对象中。我唯一关心的是最新的ping。

Ping控制器

  def location
    pings = Ping.geo_scope(:within => params[:distance], :origin => [params[:latitude], params[:longitude]])
    render :json => pings, :include => :employee, :only => [:id, :first_name, :last_name, :status, :longitude, :latitude]
    # this returns all Pings that were ever created in this location.
  end

感谢您的任何反馈和帮助!

谢谢,罗宾的帮助。你激励我提出以下建议:

employees = Employee.all

current_pings = []    
employees.each do |employee|
  current_pings << employee.ping.id
end

pings = Ping.geo_scope(:within => params[:distance], :origin => [params[:latitude], params[:longitude]]).find_all_by_id(current_pings)

render :json => pings, :include => :employee, :only => [:id, :first_name, :last_name, :status, :longitude, :latitude, :created_at]

1 个答案:

答案 0 :(得分:0)

这是未经测试的,但我的建议是使用Rails的group_by方法,这样你就可以通过employee_id对所有ping进行分组(按创建时间排序),然后遍历集合,返回密钥(employee_id)和第一个数组中的值(该员工的最新ping)。

hash = Hash.new
pings.group_by(&:employee_id).order('created_at DESC').each do |k,v|
  hash[k] = v
end
render :json => hash

可能需要进行一些调整以返回每位员工所需的确切数据,但原则上应该有效。

罗宾