# More elegant solution for "missing" has-many through ids?

**URL:** <https://www.ruby-forum.com/t/more-elegant-solution-for-missing-has-many-through-ids/185697>\
**Category:** Rails\
**Created:** [March 24, 2010, 7:14pm UTC](https://www.ruby-forum.com/t/more-elegant-solution-for-missing-has-many-through-ids/185697 "2010-03-24T19:14:21Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dudebot](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e495f1/32.png) [@Dudebot](https://www.ruby-forum.com/u/Dudebot)\
**Post date:** [March 24, 2010, 7:14pm UTC](https://www.ruby-forum.com/t/more-elegant-solution-for-missing-has-many-through-ids/185697/1 "2010-03-24T19:14:21Z")

</div>

I have LabGroup and LabDesc which have many through LabDescGroup. I’d  
like to identify LabDescs which don’t have a LabGroup. This works:

x = []  
LabDescGroup.find( :all, :select =\> ‘DISTINCT lab\_desc\_id’ ).each{ |c|  
x \<\< c.lab\_desc\_id }  
y = []  
LabDesc.find( :all, :select =\> ‘id’ ).each{ |c| y \<\< c.id }  
notfound = x - y

But is there a more elegant way? It feels like I should be able to do  
this entirely through queries, but I’m not seeing the solution.

---

<div class="post-metadata">

**Author:** ![Dudebot](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e495f1/32.png) [@Dudebot](https://www.ruby-forum.com/u/Dudebot)\
**Post date:** [March 24, 2010, 10:43pm UTC](https://www.ruby-forum.com/t/more-elegant-solution-for-missing-has-many-through-ids/185697/2 "2010-03-24T22:43:18Z")

</div>

This should do it:

LabDesc.find(:all, :conditions =\> ‘NOT EXISTS(SELECT \* FROM  
lab\_desc\_groups WHERE lab\_desc\_id=lab\_descs.id)’)

/Lasse

2010/3/24 Dudebot [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

---

<div class="post-metadata">

**Author:** ![Dudebot](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e495f1/32.png) [@Dudebot](https://www.ruby-forum.com/u/Dudebot)\
**Post date:** [March 25, 2010, 12:11am UTC](https://www.ruby-forum.com/t/more-elegant-solution-for-missing-has-many-through-ids/185697/3 "2010-03-25T00:11:40Z")

</div>

On Mar 24, 4:42 pm, Lasse B. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> This should do it:
> 
> LabDesc.find(:all, :conditions =\> ‘NOT EXISTS(SELECT \* FROM  
> lab\_desc\_groups WHERE lab\_desc\_id=lab\_descs.id)’)

Lasse, you have my “SQL Guru of the Year Award.” Many thanks,  
Craig

---

<div class="post-metadata">

**Author:** ![Dudebot](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e495f1/32.png) [@Dudebot](https://www.ruby-forum.com/u/Dudebot)\
**Post date:** [March 25, 2010, 7:16pm UTC](https://www.ruby-forum.com/t/more-elegant-solution-for-missing-has-many-through-ids/185697/4 "2010-03-25T19:16:10Z")

</div>

He he he NICE 🙂

/Lasse

2010/3/25 Dudebot [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
