Rails activerecord连接并复制数据

时间:2016-04-27 10:00:57

标签: ruby-on-rails activerecord geokit

我有一个route型号

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

step一个(包含lat和lgn)

class Step ActiveRecord::Base
  belongs_to :route
  acts_as_mappable
end

我试图让最接近的route到达给定点。

使用此请求Route.joins(:etapes).within(10, :origin => [1.23456,-5.3269])我可以获得route但我获得重复的信息(因为此route有许多步骤关闭给定点):

#<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">
]>

如何删除重复条目?

1 个答案:

答案 0 :(得分:0)

我的轻松目标是

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

这会生成GROUP BY `routes`.`id`,基本查询会为您提供所需内容。但是,如果您需要COUNT这些,那么您需要更改策略,因为COUNT将适用于组内。

我倾向于为此目的避免使用uniq解决方案,因为我发现它的表现很糟糕。不确定是否概括,但它可能与生成SELECT DISTINCT `routes`.*有关,它会比较所有列,即使您实际上只需要DISTINCT ID。