Rails 5,PostgreSQL数据库上的ActiveRecord。请使用previous_id
列,如下所示:
class Event < ApplicationRecord
belongs_to :previous, class_name: 'Event'
end
我希望将没有其他事件的所有事件都引用为“之前”事件。如何进行查询才能执行此操作?
我显然可以这样做:
Event.where.not(id: Event.pluck(:previous_id))
但我的感觉是,有一种更有效的方法来实现这一点。
答案 0 :(得分:0)
使用一些可以产生推荐SQL的ruby代码来建立@Craig Ringer的评论,你可以做这样的事情
Event.joins("left join events referencing on referencing.previous_id = events.id")
.where("referencing.id is null")