2014-05-07 81 views
1

我有一個Authorisation模型,其中有重複的內容。我想刪除所有除基於在Authorisation一個:provider列最新,留下我與最近"linkedin"授權,最近"facebook"等,等Rails:根據列銷燬除最新版本以外的所有內容

如何將我寫的方法?事情是這樣的邏輯,但它給這個錯誤(TypeError: can't convert Authorisation to Array (Authorisation#to_ary gives NilClass)):

old = Authorisation.where(provider: 'facebook') - Authorisation.where(provider: 'facebook').last 

回答

2

也許這一個:

last_record = Authorisation.where(provider: 'facebook').last 
Authorisation.where('created_at < ?', last_record.created_at).delete_all 

如果有created_at。在其他情況下,您應該獲取除最後一個以外的所有ids,並從該數組中移除具有id的記錄。

另一種方式,是應用not來查詢。像:

Authorisation.where.not(id: Authorisation.last.id).delete_all 

但它只適用於Rails 4,我認爲。

更新

這是更好的:

Authorisation.where('id != ?', Authorisation.last.id).delete_all 
相關問題