Rails(或者可能是SQL):查找和删除重复的AR对象

Jav*_*ier 0 ruby mysql sql activerecord ruby-on-rails

"位置"类(表示数据库表位置)的ActiveRecord对象具有属性"url","lat"(纬度)和"lng"(经度).

此模型上的Lat-lng组合应该是唯一的.问题是,数据库中有很多位置对象具有重复的lat-lng组合.

在执行以下操作时我需要帮助

  1. 查找共享相同lat-lng组合的对象.
  2. 如果对象的"url"属性不为空,请保留此对象并删除其他重复项.否则,只需选择最旧的对象(通过检查属性'created_at')并删除其他重复项.

由于这是一次性操作,因此欢迎SQL(MySQL 5.1兼容)中的解决方案.

rfu*_*duk 5

如果这是一次性的事情,那么我只是在Ruby中做,而不是太担心效率.我没有对此进行彻底测试,检查排序等,以确保它在您的数据库运行之前完全符合您的要求:)

keep = []
locations = Location.find(:all)

locations.each do |loc|
  # get all Locations's with the same coords as this one
  same_coords = locations.select { |l| l.lat == loc.lat and \
                                       l.lng == loc.lng }
  with_urls = same_coords.select { |l| !l.url.empty? }

  # decide which list to use depending if there were any urls
  same_coords = with_urls.any? ? with_urls : same_coords

  # pick the best one
  keep << same_coords.sort { |a,b| b.created_at <=> a.created_at }.first.id
end

# only keep unique ids
keep.uniq!

# now we just delete all the rows we didn't decide to keep
locations.each do |loc|
  loc.destroy unless keep.include?( loc.id )
end
Run Code Online (Sandbox Code Playgroud)

就像我说的那样,这绝对是糟糕的,糟糕的代码.但是,有时候只是破解那些有效的东西值得花时间思考一些"更好"的东西,特别是如果它只是一次性的话.