2

私は、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.idemployee.ping.idと比較して、そのうちの1つが従業員の最新の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

This is untested, but my suggestion would be to use Rails' group_by method so you could group all the pings by employee_id (sorted by created at) and then iterate over the collection, returning the key (the employee_id) and the first value in the array (the most recent ping for that employee).

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

Might need some tweaking to return the exact data you need in respect of each employee but should work in principle.

Robin

于 2011-03-15T11:44:18.593 に答える