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
On Monday, April 8, 2013 5:45:16 PM UTC-5, Ben Woosley wrote:
>
> 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
>
>
> On Mon, Apr 8, 2013 at 2:57 PM, Wes Gamble <[email protected] <javascript:>>wrote:
>
>> For purposes of maintenance and data cleanup, sometimes it is helpful to
>> determine if you have orphaned records in your AR backing store.
>>
>> Assuming that an AR::Base descendant has one or more belongs_to
>> associations, I propose the addition of built-in
>> "<association_name>_orphaned" scopes that would return the set of records
>> where the belongs_to association record doesn't exist. Using association
>> introspection, this would be fairly straightforward.
>>
>> However, I'm not certain about the idea of having a "built-in" scope, as
>> I'm not sure if any even exist at this point. Is this better implemented in
>> a standalone gem that would then add these scopes?
>>
>> Many thanks,
>> Wes
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Ruby on Rails: Core" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to [email protected] <javascript:>.
>> To post to this group, send email to
>> [email protected]<javascript:>
>> .
>> Visit this group at http://groups.google.com/group/rubyonrails-core?hl=en
>> .
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>>
>
>
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.