Remove object from Active Record Relation without deleting it

I'm working in Ruby on Rails 4 with Postgresql, and I've hit a bit of a snag. We have an Active Record model called AttendanceRecord which belongs to an AttendanceDay, AttendanceSwipe, Course, and CourseTimeSlot. Attendance Records were supposed to be unique on these fields, but something went wrong and duplicates snuck in. So, I wrote a method to find all of the Attendance Records which were duplicated and only keep one of them.

In the course of that method, I built an Active Record Relation of objects that shared the same attributes, like so:

records = AttendanceRecord.where(course_id: attributes[0], course_time_slot_id: attributes[1], attendance_swipe_id: attributes[2], attendance_day_id: attributes[3])

Nice relation, right?

Next, I found the object that I wanted to keep and named it to_keep. Then, I tried to remove just that object from the relation, like this:


Unfortunately, I discovered that the delete method works a little differently on a Relation than it does on an Array. Instead of simply removing the object from the list, it actually does delete it from the database (without the callbacks).

So: I'm wondering if there is a method that I'm missing that will remove my to_keep object from the Relation without actually touching the object itself. Then, I'll be able to safely call records.destroy_all and happily go about my business. :)


If you want to exclude an object from a relation you can do so by id. For example:

records.where('id <> ?',

or, thanks to @trushkevich, in rails 4 you can do:


This means that destroy_all will be called on the records you've identified already but excluding the to_keep record.

Need Your Help

Directory Access using Threadpool (.NET, IIS6)

c# threadpool

I have a large process to take place in the background of a web application and it was timing out on the main thread, so I've decided to take the Threadpool route. Unfortunately, part of this proce...

How to scroll a table horizontally?

html css

I have a table built from a dataset that is displayed in a partial view. The table is larger than the bowser.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.