t56k
t56k

Reputation: 6981

Rails: destroy all but newest based on column

I've got an Authorisation model that has outdated duplicates in it. I want to delete all except the newest based on a :provider column in Authorisation, leaving me with the most recent "linkedin" Authorisation, the most recent "facebook" etc, etc.

How would I write that method? Something like this logically but it gives this error (TypeError: can't convert Authorisation to Array (Authorisation#to_ary gives NilClass)):

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

Upvotes: 1

Views: 172

Answers (1)

Alexander Kireyev
Alexander Kireyev

Reputation: 10825

Maybe this one:

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

If there is created_at. In other case you should get all ids except last, and remove records with id from that array.

Another way, is apply not to query. Like:

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

But it work for Rails 4 only, i think.

Update

This is better:

Authorisation.where('id != ?', Authorisation.last.id).delete_all

Upvotes: 2

Related Questions