2

我正在开发一个与 Twitter 非常相似的 Rails 应用程序,该应用程序用于通过称为“pings”的状态更新来跟踪团队成员及其更新状态。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

平型号:

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.idemployee.ping.id进行比较,以查看其中一个是否是员工的最新 ping。

我无法按员工搜索,因为地理位置信息位于 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]
4

1 回答 1

0

这是未经测试的,但我的建议是使用 Rails 的 group_by 方法,这样您就可以按employee_id(按created at 排序)对所有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

可能需要进行一些调整才能返回您需要的有关每个员工的确切数据,但原则上应该可以工作。

罗宾

于 2011-03-15T11:44:18.593 回答