Rails:活动记录地址数组中的唯一地址

时间:2015-10-01 20:19:37

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2

如何检索具有相同纬度和经度的唯一地址

> addresses
=> [#<Address id: 10, country: "IN", state: "KA", latitude: "12.971513803339702", longitude: "77.59443104418949", user_id: 11>, #<Address id: 9, country: "IN", state: "KA", latitude: "12.971513803339702", longitude: "77.59443104418949", user_id: 10>]

在这种情况下,我需要任何一个ActiveRecord,因为纬度和经度具有相似的值。

1 个答案:

答案 0 :(得分:1)

您可以按纬度和经度对地址进行分组,然后在一个组中选择至少包含2个地址的地址:

addresses.
  group_by { |address| [address.latitude, address.longitude] }.
  select { |location, addresses| addresses.size >= 2 }.
  keys

根据您的使用情况,您可能希望使用distinct(请注意,您丢失了iduser_id信息):

Address.select(:country, :state, :latitude, :longitude).distinct