从Active Record Relation中删除对象而不删除它

Oni*_*shi 3 sql activerecord ruby-on-rails relational-database ruby-on-rails-4

我正在使用Postgresql在Ruby on Rails 4上工作,而且我遇到了一些麻烦.我们有一个名为Active Record的模型AttendanceRecord属于一AttendanceDay,AttendanceSwipe,Course,和CourseTimeSlot.出勤记录应该在这些领域是独一无二的,但是出了问题,重复出现了.因此,我写了一个方法来查找所有重复的出勤记录,并且只保留其中一个.

在该方法的过程中,我构建了一个共享相同属性的对象的Active Record Relation,如下所示:

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

关系不错,对吗?

接下来,我找到了我想要保留并命名的对象to_keep.然后,我试图从关系中删除该对象,如下所示:

records.delete(to_keep)

不幸的是,我发现该delete方法在一个Relation上的工作方式与在Array上的工作方式略有不同.它不是简单地从列表中删除对象,而是实际上从数据库中删除它(没有回调).

所以:我想知道是否有一个我遗漏的方法,它将to_keep从关系中删除我的对象而不实际触摸对象本身.然后,我将能够安全地打电话records.destroy_all,愉快地开展业务.:)

Sha*_*ell 5

如果要从关系中排除对象,可以通过id执行此操作.例如:

records.where('id <> ?', to_keep.id).destroy_all
Run Code Online (Sandbox Code Playgroud)

或者,感谢@trushkevich,在rails 4中你可以做到:

records.where.not(id: to_keep.id).destroy_all
Run Code Online (Sandbox Code Playgroud)

这意味着destroy_all将在您已识别的记录上调用但不包括to_keep记录.

  • 在rails 4中你可以做`records.where.not(id:to_keep.id).destroy_all` (2认同)