1

在 Rails 4 中,如何在自引用父子关系中找到所有没有子节点的记录?

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

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

我已经尝试了一个类似问题的解决方案,关于找到没有孩子的父母(在涉及自我参照模型的情况下),但它返回错误:

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

我想我已经通过调整这个答案找到了一个解决方案:

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

但是有没有比显式写出 SQL 更惯用的方法来解决问题?

4

1 回答 1

1

我不知道更红宝石的方法,但 SQL 方法会更有效的地方可能存在多个孩子:

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

人们似乎喜欢这种外连接方法,可能是因为在某些数据库中 not exists 方法的实现效率低下,但是在 not exists 的情况下,半体面的查询优化器将使用半连接,在找到第一个子节点后停止寻找其他子节点.

于 2013-08-18T10:50:06.480 回答