# Am I trying to do something silly here, as I can't figure out the best way to do it

**URL:** <https://www.ruby-forum.com/t/am-i-trying-to-do-something-silly-here-as-i-cant-figure-out-the-best-way-to-do-it/123069>\
**Category:** Rails\
**Created:** [December 13, 2007, 8:20pm UTC](https://www.ruby-forum.com/t/am-i-trying-to-do-something-silly-here-as-i-cant-figure-out-the-best-way-to-do-it/123069 "2007-12-13T20:20:01Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![DEfusion](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e68b1a/32.png) [@DEfusion](https://www.ruby-forum.com/u/DEfusion)\
**Post date:** [December 13, 2007, 8:20pm UTC](https://www.ruby-forum.com/t/am-i-trying-to-do-something-silly-here-as-i-cant-figure-out-the-best-way-to-do-it/123069/1 "2007-12-13T20:20:01Z")

</div>

I have the following models:

Account \> has\_many Companies  
Company \> has\_and\_belongs\_to\_many Accounts  
Project \> has\_and\_belongs\_to\_many Companies

I want to get all the companies that are assigned to a given account  
but are not assigned to a given company, do I have to use a custom SQL  
find in the model or is there an easier way?

-D

---

<div class="post-metadata">

**Author:** ![DEfusion](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e68b1a/32.png) [@DEfusion](https://www.ruby-forum.com/u/DEfusion)\
**Post date:** [December 13, 2007, 11:01pm UTC](https://www.ruby-forum.com/t/am-i-trying-to-do-something-silly-here-as-i-cant-figure-out-the-best-way-to-do-it/123069/2 "2007-12-13T23:01:27Z")

</div>

Yeah my mistake in the initial message, I did mean I wanted companies  
assigned to a given account but not assigned to a given project.

Thanks for the tip, I see that this does two queries so it could  
become a bit of a performance issue, but for now it’s a lot nicer than  
my custom query in the model.

Cheers,

-D

---

<div class="post-metadata">

**Author:** ![DEfusion](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e68b1a/32.png) [@DEfusion](https://www.ruby-forum.com/u/DEfusion)\
**Post date:** [December 13, 2007, 10:13pm UTC](https://www.ruby-forum.com/t/am-i-trying-to-do-something-silly-here-as-i-cant-figure-out-the-best-way-to-do-it/123069/3 "2007-12-13T22:13:43Z")

</div>

> Account \> has\_many Companies  
> Company \> has\_and\_belongs\_to\_many Accounts  
> Project \> has\_and\_belongs\_to\_many Companies
> 
> I want to get all the companies that are assigned to a given account  
> but are not assigned to a given company

Do you mean assigned to a given account but not assigned to a given  
project? If so, you could do

account.companies - project.companies

///ark
