在 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 更惯用的方法来解决问题?