Jeśli dane tabeli użytkownika, jak poniżej
User.all =>
[
#<User id: 15, name: "a", email: "[email protected]", created_at: "2013-08-06 08:57:09", updated_at: "2013-08-06 08:57:09">,
#<User id: 16, name: "a1", email: "[email protected]", created_at: "2013-08-06 08:57:20", updated_at: "2013-08-06 08:57:20">,
#<User id: 17, name: "b", email: "[email protected]", created_at: "2013-08-06 08:57:28", updated_at: "2013-08-06 08:57:28">,
#<User id: 18, name: "b1", email: "[email protected]", created_at: "2013-08-06 08:57:35", updated_at: "2013-08-06 08:57:35">,
#<User id: 19, name: "b11", email: "[email protected]", created_at: "2013-08-06 09:01:30", updated_at: "2013-08-06 09:01:30">,
#<User id: 20, name: "b11", email: "[email protected]", created_at: "2013-08-06 09:07:58", updated_at: "2013-08-06 09:07:58">]
1.9.2p290 :099 >
Identyfikatory e-mail są duplikowane, więc naszym celem jest usunięcie wszystkich duplikatów identyfikatorów e-mail z tabeli użytkowników.
Krok 1:
Aby uzyskać wszystkie rekordy e-mail odrębny identyfikator.
ids = User.select("MIN(id) as id").group(:email,:name).collect(&:id)
=> [15, 16, 18, 19, 17]
Krok 2:
Aby usunąć duplikaty z tabeli identyfikatorów użytkownika z rekordami odrębny e-mail id.
Teraz tablica ids zawiera następujące identyfikatory.
[15, 16, 18, 19, 17]
User.where("id NOT IN (?)",ids) # To get all duplicate records
User.where("id NOT IN (?)",ids).destroy_all
SZYNY 4 ** **
ActiveRecord 4 wprowadza metodę .not
który pozwala pisać o następujących Krok 2:
User.where.not(id: ids).destroy_all
jest w modelu modelu? – meetalexjohnson
@meetalexjohnson powinien być w dowolnym modelu aktywnego rekordu, który masz. –
to skały, dziękuję! –