简体   繁体   English

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

[英]Rails : Unique address from array of active record addresses

How to retrieve unique addresses which has got same latitude and longitude 如何检索经纬度相同的唯一地址

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

In this case I need any one of the ActiveRecord, as latitude and longitude are having similar values. 在这种情况下,我需要ActiveRecord之一,因为纬度和经度具有相似的值。

You could group the addresses by its latitude and longitude and then select the once with at least 2 addresses in a group: 您可以按地址的经度和纬度对地址进行分组,然后选择一次,并在组中至少包含2个地址:

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

Depending on your use case you might want to use distinct (note that you lose id and user_id information): 根据您的用例,您可能需要使用distinct (请注意,您将丢失iduser_id信息):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM