2013-03-05 22 views
0

這裏有很多類似的問題,但找不到我的好答案。使用耙子任務刪除重複項

我有EntryVote模型與字段user_id,entry_id和其他一些。

我想創建簡單的rake任務來刪除重複的user_identry_id組(沒關係whic戰績從小組左)。 做這件事的最好方法是什麼?

例如:

id, user_id, entry_id 
1,1,1 
2,1,1 
3,1,1 
4,5,6 
5,5,6 
6,7,7 

我得到:

1,1,1 
4,5,6 
6,7,7 

我知道如何選擇USER_ID,對於重複數據刪除entry_id,但不知道如何使用它以後的工作:

EntryVote.select('user_id, entry_id').group('user_id,entry_id').having('count() > 1')

+0

要確認,你想刪除'user_id'和'entry_id'相同的重複'EntryVotes'? – 2013-03-05 11:56:38

+0

nope,只是用例子編輯問題 – 2013-03-05 12:01:16

回答

0

可能不是最好的解決方案,但嘗試f或者您可以添加驗證來檢查user_id和entry_id的唯一性並嘗試保存記錄。如果記錄由於驗證而未保存並失敗,則只需刪除該記錄。我敢肯定,這是慢於:)

0

第一個選項如果你想要的列entry_iduser_id是一個獨特的外鍵,它包含一個特殊的SQL刪除以下rake任務聲明,就可以

task 'delete_duplicates' => :environment do 
    puts "Removing duplicates in table entry_votes" 
    puts "Entries before: #{n1=EntryVote.count}" 
    sql = "delete e1 from entry_votes e1, entry_votes e2 "+ 
      "where (e1.user_id = e2.user_id) and (e1.entry_id = e2.entry_id) "+ 
      "and (e1.id > 12.id);") 
    ActiveRecord::Base.connection.execute(sql); 
    puts "Entries after: #{n2=EntryVote.count}, #{n1-n2} duplicates removed" 
    end 

另請參閱此SO question about duplicates或此文章how to delete duplicates using SQL