Proposed new ActiveRecord feature: Built-in "orphaned" scope for AR objects

Hey Wes,

If you use foreign key constraints, then all orphaned records would have the foreign key set to null. If not, you’d have to do an outer join to determine what is orphaned. Given this divergence, IMO this is best left to the author.

-Ben

Ben,

Depending on how things are set up, you may or may not have NULL values in the foreign key column. In either case, this query:

Given:

X: an AR::Base descendent class

association_class: the belongs_to association class (discovered via association reflection)

foreign_key: the foreign key to the belongs_to association class (discover via association reflection)

X.where(“{foreign_key} NOT IN (SELECT {association_class.primary_key} FROM {association_class.table_name})”)

will give you all orphaned records for X with respect to association_class.

W