# How to describe negative find condition in has\_many

**URL:** <https://www.ruby-forum.com/t/how-to-describe-negative-find-condition-in-has-many/183456>\
**Category:** Rails\
**Created:** [February 14, 2010, 8:50pm UTC](https://www.ruby-forum.com/t/how-to-describe-negative-find-condition-in-has-many/183456 "2010-02-14T20:50:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![cpr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/439d5e/32.png) [@cpr](https://www.ruby-forum.com/u/cpr)\
**Post date:** [February 14, 2010, 8:50pm UTC](https://www.ruby-forum.com/t/how-to-describe-negative-find-condition-in-has-many/183456/1 "2010-02-14T20:50:36Z")

</div>

I have a Teams that has\_many Players.

I need to get the list of Teams that have no active players (whether  
they have 0 players or they have a lot of players all of whom are non-  
active).

Can’t figure out the conditions for doing this other than subtracting  
the ones with active players from the list of all teams. The issue is  
that I don’t want teams with _some_ non-active players, I need the  
teams which have only non-active players.

Here’s how I’m doing it now. I assume that there’s a better way so  
will appreciate seeing the magic.

Thanks,

-Chris

Player \< AR::Base

validates\_inclusion\_of :status, :in =\>  
[:active, :inactive, :injured, :dead]

end

Team \< AR::Base

has\_many :players

named\_scope :with\_active\_players, {  
:include =\> :players,  
:conditions =\> [“players.status = ?”, “active”],  
:group =\> “teams.id”, # no dups  
:order =\> ‘teams.name’  
}

def self.without\_active\_players  
(Team.find(:all) - Team.with\_active\_players).sort\_by { |t|  
t.name }  
end

end

---

<div class="post-metadata">

**Author:** ![cpr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/439d5e/32.png) [@cpr](https://www.ruby-forum.com/u/cpr)\
**Post date:** [February 14, 2010, 9:16pm UTC](https://www.ruby-forum.com/t/how-to-describe-negative-find-condition-in-has-many/183456/2 "2010-02-14T21:16:56Z")

</div>

Try:

named\_scope :without\_active\_players, :conditions =\> “NOT EXISTS(SELECT \*  
FROM players WHERE team\_id=teams.id AND status=‘active’)”, :order =\>  
“name”

Does this work?

Lasse

2010/2/14 cpr [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

---

<div class="post-metadata">

**Author:** ![cpr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/439d5e/32.png) [@cpr](https://www.ruby-forum.com/u/cpr)\
**Post date:** [February 14, 2010, 10:55pm UTC](https://www.ruby-forum.com/t/how-to-describe-negative-find-condition-in-has-many/183456/3 "2010-02-14T22:55:16Z")

</div>

He shoots. He scores!

Thanks much for the insight.

-Chris
