如果您的用戶表數據如下面
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 >
電子郵件ID是重複的,所以我們的目標是從用戶表中刪除所有重複的電子郵件ID。
第1步:
要獲得所有不同的電子郵件記錄ID。
ids = User.select("MIN(id) as id").group(:email,:name).collect(&:id)
=> [15, 16, 18, 19, 17]
第2步:
刪除重複的ID從用戶表具有鮮明的電子郵件記錄ID。
現在,ids數組包含以下ID。
[15, 16, 18, 19, 17]
User.where("id NOT IN (?)",ids) # To get all duplicate records
User.where("id NOT IN (?)",ids).destroy_all
**軌道4,5 **
ActiveRecord的4引入了.not
方法,它允許你寫步驟2中的以下內容:
User.where.not(id: ids).destroy_all
這是在型號模型? – meetalexjohnson
@meetalexjohnson它應該在任何主動記錄模型中。這個岩石 –
,謝謝! –