2011-03-14 68 views
2

我正在開發一個與Twitter非常相似的Rails應用程序,該應用程序用於通過狀態更新來追蹤團隊成員及其更新狀態,坪。 Twitter將這些狀態的「推文」稱爲「。通過查詢他們的最新狀態更新位置來查找特定位置的用戶

本申請的要旨是這樣的:

員工(:如first_name,:姓氏)
平(:日期時間,:狀態,:緯度,:經度)

僱員型號:

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對象中。而我唯一關心的是最新的。

平控制器

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] 

回答

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 

可能需要一些調整以返回您需要的關於每個員工的確切數據,但應該在原則上工作。

羅賓