Remove object from Active Record Relation without deleting it.
I am working in Ruby on Rails 4 with Postgresql and I am hit a bit. We have an Active Record model named AttendanceRecord
, which is owned by AttendanceDay
, AttendanceSwipe
, Course
and CourseTimeSlot
. The attendance reports were supposed to be unique in these fields, but something went wrong and duplicates came in. So, I wrote a method to find all the attendance records that were duplicated and keep only one of them.
During this method, I created Active Record Relation objects that have the same attributes, for example:
records = AttendanceRecord.where(course_id: attributes[0], course_time_slot_id: attributes[1], attendance_swipe_id: attributes[2], attendance_day_id: attributes[3])
Nice attitude, right?
Then I found the object I wanted to keep and named it to_keep
. Then I tried to remove only that object from the relationship, for example:
records.delete(to_keep)
Unfortunately, I found that the method delete
works slightly differently with respect to Relation than it does with an array. Instead of just removing the object from the list, it actually removes it from the database (no callbacks).
So: I am wondering if there is some method I am missing that will remove my object to_keep
from the Relation without actually touching the object itself. Then I can call you with confidence records.destroy_all
and gladly tell you about my business. :)
source to share
If you want to exclude an object from a relationship, you can do so by id. For example:
records.where('id <> ?', to_keep.id).destroy_all
or, thanks to @trushkevich, in rails 4, you can do:
records.where.not(id: to_keep.id).destroy_all
This means that it destroy_all
will be called already by entries, with the exception of entries to_keep
.
source to share