ruby-on-railsactiverecordgeokit

Rails activerecord joins and duplicates data


I'm having a route model

class Route < ActiveRecord::Base
  has_many :etapes
  acts_as_mappable :through => :steps
end

and a step one (that contains lat and lgn)

class Step ActiveRecord::Base
  belongs_to :route
  acts_as_mappable
end

I'm trying to get the closest route to a given point.

With this request Route.joins(:etapes).within(10, :origin => [1.23456,-5.3269]) I can get the routes but I got duplicates informations (because this route has many steps closes to the given point):

#<ActiveRecord::Relation [
#<Route id: 1, created_at: "2016-03-26 21:53:01", updated_at: "2016-03-26 21:53:01">, 
#<Route id: 1, created_at: "2016-03-26 21:53:01", updated_at: "2016-03-26 21:53:01">
]>

What can I do to remove duplicates entries ?


Solution

  • My easy go-to would be

    Route.joins(:etapes).within(10, :origin => [1.23456,-5.3269]).group(:id)

    This generates a GROUP BY `routes`.`id` which for basic queries will get you what you want. If you need to COUNT these, though, then you need to change strategies, since the COUNT will apply within-group.

    I tend to avoid the uniq solution for this purpose as I've found it to perform miserably. Not sure if that generalizes, but it may have to do with it generating a SELECT DISTINCT `routes`.*, which compares all columns even though you really only need the DISTINCT by id.