具有“链表”类型自引用的模型,如何仅获取未引用的模型?

时间:2017-11-10 04:01:07

标签: ruby-on-rails postgresql activerecord

Rails 5,PostgreSQL数据库上的ActiveRecord。请使用previous_id列,如下所示:

class Event < ApplicationRecord
  belongs_to :previous, class_name: 'Event'
end

我希望将没有其他事件的所有事件都引用为“之前”事件。如何进行查询才能执行此操作?

我显然可以这样做:

Event.where.not(id: Event.pluck(:previous_id))

但我的感觉是,有一种更有效的方法来实现这一点。

1 个答案:

答案 0 :(得分:0)

使用一些可以产生推荐SQL的ruby代码来建立@Craig Ringer的评论,你可以做这样的事情

Event.joins("left join events referencing on referencing.previous_id = events.id")
     .where("referencing.id is null")