在自我指涉关系中找到没有孩子的父母

时间:2013-08-17 18:04:25

标签: ruby-on-rails activerecord ruby-on-rails-4

在Rails 4中,我怎样才能找到所有自我参照亲子关系中没有孩子的记录?

该模型是一项任务,可能只有一个父任务和多个子任务。这是型号代码:

class Task < ActiveRecord::Base
  belongs_to :parent, class_name: 'Task'
  has_many :children, class_name: 'Task', foreign_key: 'parent_id'
end

我尝试了similar question解决方案,找到没有孩子的父母(在涉及自引用模型的情况下),但它返回错误:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: children.id

我认为我已经通过调整this answer给出了一个解决方案:

scope :without_children, joins("left join tasks as children on children.parent_id = tasks.id").where("children.parent_id is null")

但有没有更惯用的方法来解决问题,而不是明确地写出SQL?

1 个答案:

答案 0 :(得分:1)

我不知道更多rubyish方法,但SQL方法在多个子项可能存在的情况下会更有效:

scope :without_children, where("not exists (select null from children where children.parent_id = tasks.id)")

人们似乎喜欢那种外连接方法,可能是因为某些数据库中不存在方法的实现效率低下,但是如果不存在,那么半正式查询优化器将使用半连接来停止寻找其他子节点找到第一个。