views:

81

answers:

0

I'm using Datamapper 1.0 with sinatra and sqlite3 as backend.

I have some devices, which have multiple locations, and I usually only want the latest location of a device. The problem is that the generated SQL for the above line will query all locations for the device not just the latest one (and a device can have 10-20k locations). This is clearly not optimal, so I'm asking: am I doing something wrong? Or datamapper works this way and I have to resort back to plain SQL? Is there a better workaround?

I have the following data schema:

class Location
  include DataMapper::Resource
  property :id, Serial
  property :lat, Integer
  property :lon, Integer
  property :time, Time
  belongs_to :device
end

class Device
  include DataMapper::Resource
  property :id, Serial
  has n, :locations

  def lat # and lon
    locations.first(:order => [:time.desc]).lat
  end
end 

Here a call to d.first.lat (where d is a Device acquired using d = Devices.all) will result in a query of all the locations, instead of only the first matching one.

I have only these two models, and the querying is simple too:

  • In controller: @devices = Device.all
  • In view: @devices.each { |d| d.lat }
  • And in model: def lat; locations.first.lat; end

Thanks.